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!
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.
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