tedwards947
tedwards947

Reputation: 380

Absolute fastest way to get ID of underlying jQuery element?

I am wondering about the fastest way to get the ID of an element which wrapped in a cached jQuery object. I have n number of elements to iterate over and so I want to make sure I'm using the most efficient code possible.

Which one of these is fastest/any other suggestions? Any cost/benefit analysis would be much appreciated.

//cached jquery object using .attr()    
$myElement.attr("id");

//getting the native JS element and getting the ID that way
$myElement[0].getAttribute('id');

Thanks!

Upvotes: 0

Views: 335

Answers (1)

VisioN
VisioN

Reputation: 145428

The following way is the fastest:

var id = $myElement[0].id;

Here you don't call any functions, just address the object properties.

enter image description here

JSPerf: http://jsperf.com/jquery-get-object-property

Upvotes: 3

Related Questions