Let's say i have a html table like this:
<table>
<tr id="a" class="red"><td>test</td></tr>
<tr id="b" class="red"><td>test</td></tr>
<tr id="c" class="red"><td>test</td></tr>
<tr id="d" class="red"><td>test</td></tr>
<tr id="e" class="green"><td>test</td></tr>
<tr id="f" class="blue"><td>test</td></tr>
</table>
How can i loop through/get all ids of class "red" using jQuery?
Use .each()
var idArray = [];
$('.red').each(function () {
idArray.push(this.id);
});
You can do this using the .map()
method like:
var ids = $('.red').map(function () {
return this.id;
}).get().join();
console.log(ids); // Result: a,b,c,d
Explanation:-
Here the below code:-
$('.red').map(function () {
return this.id;
})
we are passing each element in the current matched set .red
through a function, producing a new jQuery object containing the return values, which is the id
of the each element.
So, the above code results in a new jQuery object like:
["a", "b", "c", "d", prevObject: jQuery.fn.init[4], context: document]
Next, .get()
is used to retrieve the DOM elements matched by the new jQuery object above. So, after using .get()
our result is like:
["a", "b", "c", "d"]
Next, .join()
method joins all elements of an array (which we got after using .get()
) into a string like:
a,b,c,d
If we use .join(', ')
we can get some space after comma like:
a, b, c, d
or a .join('~')
would result in:
a~b~c~d
You can always modify the separator in the .join()
based on your requirement.
var ids = $('.red').map(function() {
return this.id;
}).get().join();
console.log(ids); // Result: a,b,c,d
.red{color:red;}
.green{color:green;}
.blue{color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table>
<tr id="a" class="red"><td>test</td></tr>
<tr id="b" class="red"><td>test</td></tr>
<tr id="c" class="red"><td>test</td></tr>
<tr id="d" class="red"><td>test</td></tr>
<tr id="e" class="green"><td>test</td></tr>
<tr id="f" class="blue"><td>test</td></tr>
</table>
Using $.map() as easy as
//ids is an array of the element ids with class red
var ids = $('table .red').map(function(){
return this.id
}).get()
Demo: Fiddle
$('.red').each(function(){
confirm(this.id);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With