Reputation: 3577
Today i'm very stack with a Work and jQ. I was get a morning for it but i can't resolve it :(. My Work here:
<div class="container">
<p class="test">a</p>
<div>
<p class="test">a</p>
</div>
</div>
In normal, i can using jQ with each function for
select all <p class="test">a</p>
EX:
$(".test").each(function() {
$(this).text('a');
});
But i hear everyone talk that, for
function get a less timeload than each
function. Now i want using for
instead of each
.. but i don't know how to write code jQ in this case.
Somebody can help me!. thankyou!
Upvotes: 4
Views: 4306
Reputation: 1070
Another alternative:
for (var i = 0; i < $('.test').length; i++){
var element = $('.test').eq(i);
}
Upvotes: 1
Reputation: 490667
I wouldn't worry about it unless you were iterating through hundreds of them.
for
loop is usually used with normal DOM (aka without jQuery) traversing, like...
var elements = document.getElementById('something').getElementsByTagName('a');
var elementsLength = elements.length;
for (var i = 0; i < elementsLength; i++) {
elements[i].style.color = 'red';
}
Caching of elementsLength
is a good idea so it is not calculated every iteration. Thanks to CMS for this suggestion in the comments.
Just adapt that for your jQuery object if you wanted to do it with jQuery.
Replace elements
variable with your jQuery collection, like $('#something a')
. I think you may need to rewrap the object if you need to do any more jQuery stuff with it.
Upvotes: 7
Reputation: 93643
This article shows that each()
has no significant performance penalty until you get into the hundreds of thousands of looped-over items.
Upvotes: 1
Reputation: 60590
One thing to watch out for is that using an ordinal accessor on the result of a jQuery selection will return a native DomElement. If you want to use jQuery methods on them, you have to re-wrap them:
var testElements = $('.test');
for (var i = 0; i < testElements.length; i++) {
// Using $() to re-wrap the element.
$(testElements[i]).text('a');
}
I'd second what others have said though. Unless you're dealing with many elements, this is premature optimization. Re-wrapping the elements to use the .text() method may even bring it back to no gain at all.
Upvotes: 5
Reputation: 9423
have you tried the obvious solution?
var nodes = $(".test");
for(var i = 0; i < nodes.length; i++)
{
var node = nodes[i];
}
Upvotes: 1