Reputation: 166
I am creating elements using jQuery and assigning them IDs in the process. Later in my code, I want to access these elements via their ID. However, I am unable to do this with jQuery. If I use just core JS, it works, though. Why might this be?
var createTable = function(rows, columns, height, width) {
var $table = $("<table>");
$("body").append($table);
for (var i = 1; i < rows + 1; i++) {
var $tr = $("<tr>");
$table.append($tr);
for (var j = 1; j < columns + 1; j++) {
var $td = $("<td>", { id: i + "." + j });
$td.css("height", height + "px").css("width", width + "px")
.css("border", "1px black solid");
$tr.append($td);
}
}
}
createTable(4, 4, 150, 100);
Does not work:
$("#1.1").css("border", "1px red solid");
Works:
var onePointOne = document.getElementById("1.1");
onePointOne.style.border = "1px red solid";
Upvotes: 0
Views: 60
Reputation: 118
Try this one, it will work:
$("#1\\.1").css("border", "1px red solid !important");
Upvotes: 1
Reputation: 85545
The .
operator denotes to the class so it would search for id 1 and it's class 1 but you are not accessing to those but your id contains .
a meta-character for which you need to use slash for escaping the meta character:
$("#1\\.1").css("border", "1px red solid");
see more information about this here
But I would recommend to you not to use .
operator for your id, you could assign it like 1-1
for which you can easily access like $('#1-1')
And still more I would recommend you not to use id starting from number.
Upvotes: 2
Reputation: 2690
The dot has special meaning in selectors: they are class selectors. You will need to escape the dot to find the correct id:
$('#1\\.1')...
Upvotes: 3