josephmisiti
josephmisiti

Reputation: 9974

JQuery Selector Re-Write

I do this kind of thing all over the place, and I am looking for the most efficient (both computationally + syntactically) way to execute:

ids =[]
$('tr.selectON td').each( function() { 
    var answer_query = $(this).attr('id');
    if ( answer_query !== undefined ) { 
        ids.push( answer_query ) 
    }   
});

I have access to underscore.js, which I suspect will help.

Upvotes: 1

Views: 70

Answers (2)

Rajat Singhal
Rajat Singhal

Reputation: 11264

ids = $("tr.selectON td[id]").map(function() { return this.id; }).get();

Documentations :

To get elements with id attribute http://api.jquery.com/attribute-contains-prefix-selector/

To filter id attribute http://api.jquery.com/map/

To convert result into array http://api.jquery.com/get/

Upvotes: 10

MaxPRafferty
MaxPRafferty

Reputation: 4977

You can make it simpler, cant speak to the JQuery performance though:

ids =[]
$('tr.selectON td[id^=""]').each( function() { 
        ids.push( this.id ) 
});

"this" in the function is already a dom object, so you have direct access to its id.

Upvotes: 0

Related Questions