0

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";
stefvhuynh
  • 146
  • 9

3 Answers3

3

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')...
sahbeewah
  • 2,677
  • 1
  • 10
  • 18
2

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.

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
1

Try this one, it will work:

$("#1\\.1").css("border", "1px red solid !important");
Arulkumar
  • 12,153
  • 12
  • 44
  • 61
Aniket
  • 118
  • 6