Use a jQuery selector to target an element with a numerical ID by utilizing CSS escape characters

How do I change the background color of a div with id='1' and class='std' to red using jQuery (assuming i equals 1)?

$("#" + i).css("background-color", "red");

Here is the code snippet:

           for(var i=0 ; i< info.length ; i++ ){

                var div_std ='<div id="'+i+'" class="std"> <p> Name :<b> '+info[i].nom_etud + ' </b></p> <hr><p> Abs Hours : '+info[i].hr_cours +'</p>' ;
                div_std+='<p> TPs Hours : '+info[i].hr_tp+'</p><section id="footstd"><button type="button" name="">Mark as absent</button><img src="images/abs.png"></section>'+'</div>';            

                if(info[i].col == 1)
                {
                    $(function() {
                      $("#\\" + i.toString().charCodeAt(0).toString(16)).css("background", "red");
                    });
                }
                else if(info[i].col == 2)
                    $(function() {
                      $("#\\" + i.toString().charCodeAt(0).toString(16)).css("background", "blue");
                    });
                else if(info[i].col == 3)
                    $(function() {
                      $("#\\" + i.toString().charCodeAt(0).toString(16)).css("background", "green");
                    });
                $(".main").append(div_std);   //Display the students name
            }

Answer №1

When dealing with ids that have numbers or special characters at the start, it's essential to utilize CSS escapes:

$(function() {
  // #1 should be escaped as #\31
  $("#\\31").css("background", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="1">div</div>

Here is a more detailed example for ids ranging from 1 to 100:

$(function() {
  var i, selector, $div;
  for (i = 1; i <= 100; i++) {
    selector = "#\\" + i.toString().charCodeAt(0).toString(16) + " " + i.toString().substr(1);
    $div = $('<div id="' + i + '"><code>id: ' + i + ', selector: ' + selector + '</code></div>').appendTo("body");
    $(selector).css("background", "green");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

For your specific scenario, using inline styles directly to change background color would be a straightforward solution instead of employing CSS selectors:

var bgcolor = ["red", "blue", "green"][info[i].col - 1] || "transparent";
var div_std = '<div id="' + i + '" class="std" style="background-color: ' + bgcolor + '">...'

Answer №2

Like @D4V1D pointed out, accessing #1 through CSS is not possible, but with jQuery it can be done— even in a straightforward manner without using div[id=x]. Here's how:

var i = 1;

$('#' + i).css('background-color', 'red');

Give it a try yourself: http://jsfiddle.net/wn7njfuc/

If the solution isn't working for you, chances are your jQuery wasn't loaded properly.

EDIT 1

As per the OP's comment, they are using Jade. Therefore, try adding this just before your div:

script.
    $(document).ready(function () {
      var i = 1;
      $('#' + i).css('background-color', 'blue');
    });

Answer №3

IDs must not start with numbers when using CSS selectors.

Below is the correct way to achieve this:

jQuery(function($) {
    $('div[id='+i+']').css("background-color", "blue");
});

Update

I made an error, #1 does not work in pure CSS but can be used in jQuery (referencing @GuilhermeOderdenge's response). Therefore, there is no requirement for using $('div[id=1]').

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using CSS to remove the background of a dropdown button in a <select> element

I need to style a <select> element so that it appears like plain text until clicked, revealing the pulldown choices. Ideally, I would like to include small arrows to indicate multiple options, but I can add those as image overlays if necessary. My p ...

What could be causing the bullet not to appear in Internet Explorer 6

It is visible in Firefox, but not in IE (specifically IE6). <style type="text/css"> li { list-style-type:disc; } </style> <div style="margin: 2px auto 15px; padding: 5px 0px; width: 480px; text-align: center;"> <ul style="margin: 0; ...

Tips for utilizing AJAX and jQuery to fetch content from WordPress pages

Let me simplify my request so it's easy to grasp. I have a WordPress website with multiple pages. My goal is to create a main page called "Work" and add a submenu with links to "Videos", "Audio", "Writing", and "Design" pages. Here's the catch - ...

Angular project encounters error message: 'JQuery<HTMLElement>' type does not have property 'bxSlider'

I'm encountering an issue with an Angular project where I'm attempting to utilize bxSlider. After following the installation instructions from the official website , it seems that either VS Code or Angular is not recognizing the plugin. For inst ...

Display an image when the iframe viewport is reduced in size by utilizing media queries

I am looking to showcase a demo.html page within a 400px square iframe. When the viewport is smaller than 400px, I want demo.html to only display an image. Then, when clicking on that image in demo.html, the same page should switch to fullscreen mode. Sim ...

Is there a way to automatically play videos without any audio?

Is there a way for my video to automatically start playing when the page loads, without sound? I want it to function similar to the video on this webpage: . I've experimented with various jQuery, JavaScript, and CSS techniques from online resources, ...

Forced line break at particular point in text

I would love to implement a line break right before the "+" character, either using css styling or through a different method. Is this task achievable? #myDiv{ width: 80% } #myP{ c ...

Blog Format Featuring Side-by-Side Columns

Is there a way to achieve horizontal columns that don't cut off articles and flow seamlessly into the next column? I want the columns to have varying heights, such as Post A at 60% height, followed by Post B at 40% height, then Post C at 30%, and fina ...

Is there a way for me to enable autoplay on the Slice Slider?

I'm struggling to enable autoplay on a slider I have here. Is it possible to quickly set this up in the var settings? I attempted to insert the setInterval(spin, 3000); command before and after the init lines, but it hasn't been successful so fa ...

How can I remove a specific JSON object from localStorage based on the data associated with the element that is currently being clicked on?

Unique Scenario A user interacts with an element, triggering a change in the background image and storing data related to that element in localStorage: this process functions correctly. Next, the toggle variable is set to 0, the background image change ...

The jQuery scrollTop function seems to be malfunctioning following an ajax request

My ajax call is functioning properly, but I am experiencing an issue with the scrollTo plugin from JQuery. It is not positioning the content where I want it to be located below. //This function reveals the email body when a list item is clicked. jQue ...

What is the process for obtaining a hashed URL from an AJAX response after submitting a form?

I am currently using a WordPress exchange plugin and I am looking to streamline the bidding process by making it ajax-based. When I submit one of the forms, the page redirects to a blank page displaying a response that looks like this: {"status":"success" ...

The CSS of the Sendgrid template is being overlooked

I have utilized Sendgrid to create the template mentioned below: https://i.sstatic.net/TFQfl.png In order to send this template using my Node server, I have developed the module provided in the code snippet: /* * Created by root on 6/6/16. */ var path ...

Determine if an object is already present in a JSON array by comparing their respective IDs

I have a shopping cart stored in JSON format. [{"tuote":{"id":"2","name":"Rengas 2","count":16,"price":"120.00"}},{"tuote":{"id":"1","name":"Rengas 6","count":"4","price":"25.00"}},{"tuote":{"id":"4","name":"Rengas 4","count":"4","price":"85.00"}}] Form ...

Merge information from two XML files to create dynamically generated line items

Utilizing jQuery, I am fetching XML data from two distinct XML files to construct line items within an unordered list on a single-page PhoneGap application. Each XML file provides a portion of the line item - descriptive text and an href for an mp4 file. ...

Unlimited image rotation with JQuery

I'm currently working on a project where I have a series of images that are moving left or right using the animate() function. My goal is to create a loop so that when the user clicks "next", the last image transitions to the first position seamlessly ...

Concealed Button in Javascript

I've got a JavaScript function that effectively hides a link or button for a specific period of time. JavaScript: <script type="text/javascript"> function showNextButton() { document.getElementById("nextbutton").style.visibility = " ...

How can I locate the element immediately preceding $(this)?

Struggling to retrieve the value of the $(.subname) when the .bigadminbutton is clicked and calling the updateSub() function. I have tried various methods like prev, sibling, parent, children, find, but none seem to work. This minor task is taking up too ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...