Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - find all IDs in a class

Tags:

jquery

class

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?

like image 674
eye Avatar asked Sep 06 '13 11:09

eye


4 Answers

Use .each()

var idArray = [];
$('.red').each(function () {
    idArray.push(this.id);
});
like image 145
Anton Avatar answered Sep 24 '22 21:09

Anton


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>
like image 21
palaѕн Avatar answered Sep 25 '22 21:09

palaѕн


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

like image 27
Arun P Johny Avatar answered Sep 26 '22 21:09

Arun P Johny


$('.red').each(function(){
    confirm(this.id);
});
like image 23
Jaime Montoya Avatar answered Sep 26 '22 21:09

Jaime Montoya