Home / Loop through selected elements with jQuery

Loop through selected elements with jQuery

There may be times when you need to loop through elements in jQuery to collect information, change state or some other nifty trick that can’t be done easily using jQuery’s various selection etc functions. 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.

PLEASE NOTE: This post has been revised and you are advised not to use the method presented here. Refer to my updated post here which shows how to loop through the elements with jQuery using the .each() function. This only requires a single lookup in the DOM whereas the method here requires two lookups for each <a> tag in #example.

 

Basic usage

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

for(var i = 0; i < $('#example a').length; i++) {
    // do something
}

Example HTML

This is the example HTML used by the function below:

<ul id="example">
    <li><a href="https://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 = '';
    for(var i = 0; i < $('#example a').length; i++) {
        hrefs += $('#example a')[i].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.

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.