JQUERY get content of each table cell with id = xyz
I have the following HTML table:
<table class="xyz">
[...]
<tbody>
[...]
<tr>
[...]
<td class="id9">some content</td>
<td class="id39">some content</td>
</tr>
[...]
<tr>开发者_如何学C;
[...]
<td class="id9">some content</td>
<td class="id39">some content</td>
</tr>
[...]
</tbody>
[...]
So I have some cells with ID's and now I want to get the content of all cells with id=39
for example.
What I tried is to use the each function on all td's and then check the id with value.attr('id')
and finally check the id with contains.
I'm quite new to jQuery, so what I tried is a mess.
Hope someone has a idea.
Firstly, you seem to be confused between id
and class
. You are using class
in your example markup, which is the correct approach, as you cannot have duplicate id
values in the same document. However, you keep mentioning that you want to select items based on id
.
The class selector, .
, will let you select all elements with a specific class. So in your case:
$(".id39")
Will select all elements with class="id39"
. You can then iterate over the set of matched elements with each
and do whatever you like with the value:
$(".id39").each(function() {
var currentValue = $(this).text();
});
If you just want to apply some jQuery method to all selected elements, then you don't need to bother with the each
. For example, to hide all matched elements:
$(".id39").hide(); //Hides all elements with class "id39"
Those aren't ids, they are classes. You can use the jQuery selector $("td.id39");
to retrieve the table cell. IDs are unique while classes can apply to many elements.
Extending Tyler Eaves answer, if you wanted to collect all of the content to a concatenated string, you could simply do...
var text = '';
$('td.id9').each(function(i, elem) { text += $(elem).text(); });
Furthermore, you could roll it into a re-usable function that takes the ID number as an input parameter...
function GetTdContent(id) {
var text = '';
$('td.id' + id).each(function(i, elem) { text += $(elem).text(); });
return text;
}
Just for clarity your example shows tds with the class set to id39 not the id attribute, assuming that this is correct you will want to use something like this:
$(".id39").each( function () {
//do some stuff
});
More info on the JQuery each function can be found in the API Docs
Something like
$("td.id9").each(function(){
....
});
should work.
精彩评论