css3 - jQuery selector for element with numeric id using CSS escapes -


i'm trying give red color div id='1' class='std' using jquery (i equals 1):

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

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 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 students name             } 

to match ids start numbers or special characters should use css escapes:

$(function() {    // #1 should escaped #\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>

and lengthier example ids 1 ... 100:

$(function() {    var i, selector, $div;    (i = 1; <= 100; i++) {      selector = "#\\" + i.tostring().charcodeat(0).tostring(16) + " " + i.tostring().substr(1);      $div = $('<div id="' + + '"><code>id: ' + + ', 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>

having said that, in case can use inline styles change background color instead of using css selectors:

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

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -