Flynn
Flynn

Reputation: 6181

Javascript: Easiest way to make a list of elements

I have a div and a list with some items in it:

<div id="myDiv">
<ul>
    <li><a>Item 1</a></li>
    <li><a>Item 2</a></li>
    <li><a>Item 3</a></li>
</ul>

How could I easily make a Javascript array of the 'a' elements knowing that the number of items may change?

Upvotes: 0

Views: 63

Answers (3)

J.Wells
J.Wells

Reputation: 1759

In plain old javascript (no jQuery needed):

    var myDiv = document.getElementById('myDiv');
    var allAnchors = myDiv.getElementsByTagName('a');
    for (var i = 0; i < allAnchors.length; i++) {
        //do something with each allAnchors[i] node
        document.write(allAnchors[i].innerHTML + '<br />');
    }

Upvotes: 0

I Hate Lazy
I Hate Lazy

Reputation: 48761

If you want a static list:

var mylist = $('#myDiv > ul > li > a').toArray();

But you wrote "...knowing that the number of items may change". If this means you want a "live list" that updates with DOM changes, then do this:

var mylivelist = document.getElementById("myDiv")
                         .getElementsByTagName("a");

This list will update when items are added or removed. It makes the assumption that there are no other <a> elements in the <div>. If there are, you'll need to adjust.

Upvotes: 3

Glenn Slaven
Glenn Slaven

Reputation: 34203

If you use jQuery then it's

$('#myDiv a')

if no jQuery then just this

document.getElementById('myDiv').getElementsByTagName('a')

Upvotes: 0

Related Questions