Reputation: 65
I need to get the value of a td by both it's class and it's ID. I have the following code at the moment, which doesn't seem to work.
for (a = 0; a < count; a++)
{
var warehouse = $('.warehousename #' + a).text();
console.log(warehouse);
}
The TD code is as follows;
echo "<td class='warehousename' id='".$i."'>" . $array[$i]['warehouse'] . "</td>";
The i and a variable are correct.
Upvotes: 0
Views: 681
Reputation: 34199
If your ID is not unique (but it shouldn't be so), you can use the following selector.
var warehouse = $('.warehousename#' + a).text();
And again: it shouldn't be so. HTML id
attribute stands for unique identificator in HTML markup. If you want to set your warehouses' id
to some tds for future use, you should use custom attributes.
For example, in PHP:
echo "<td class='warehousename' data-id='".$i."'>" . $array[$i]['warehouse'] . "</td>";
JS:
var warehouse = $('.warehousename[data-id="' + a + '"]').text();
It looks better and it is valid.
With that approach you can assign numbers to data-id
.
It would be incorrect in case of HTML id
attribute.
Upvotes: 2
Reputation: 388316
Since ID of an element must be unique you could just say
var warehouse = $('#' + a).text();
Your selector '.warehousename #' + a
looks for an element with the given id(value of a
) which is a descendant of an element with class warehousename
, but in your case the element itself have the class so it won't return any element
Upvotes: 1