Home / Loop through selected elements with jQuery (Revised)

Loop through selected elements with jQuery (Revised)

Earlier today I posted how to loop through elements in jQuery but as pointed out by Bloid at DZone it wasn’t a very good way of doing it. This post is a revision to that earlier post and thanks to Bloid for letting me know a much better (and more jQuery way) of doing this. This post has an example of looping through elements with jQuery by getting all the href attributes from the <a> tags of a selected element.

Basic usage

To loop through all the <a> tags belonging to the #example element, do this:

$('#example a').each(function(idx, item) {
    // do something
});

Example HTML

This is the example HTML used by the function below:

<ul id="example">
    <li><a href="https://www.electrictoolbox.com/">Link 1</a></li>
    <li><a href="http://www.example.com/">Link 2</a></li>
    <li><a href="http://www.google.com/">Link 3</a></li>
</ul>
<p><input type="button" value="Click Me" onclick="example()" /></p>

Example Javascript

And here’s the example Javascript. It loops through the <a> tags within the #example <ul> and adds the hrefs to a string. This is then shown in an alert dialog.

function example() {

    var hrefs = '';  
    $('#example a').each(function(idx, item) {  
        hrefs += item.href + 'n' ;  
    });
    window.alert(hrefs);

}

Working example

And finally, here’s the example in action. If you are viewing this in a RSS feed reader then clicking the button below won’t work. You will need to click through to this article in a web browser to view the demo working.

Improvements from the original post

In my original post I looped through the elements using for( … ) style loop which requires multiple lookups in the DOM. Using the jQuery each() function instead only requires 1.

I did some benchmark testing and the code in my original post took 6x longer to run than the code in this post, for 3 <a> tags and 27x longer for 15 <a> tags which shows that the .each() function takes only marginally more time to process when more elements are present and just how inefficient using a for( … ) loop is in this instance.

Conclusion

jQuery makes it really easy to loop through elements to get information, change state etc. There are already many useful functions for applying changes quickly to elements and being able to loop through elements as shown in this post adds another useful method for manipulating information in a web page with jQuery.