2
<div id="nav">
    <ul id="linkselect">
      <li class="important" ><a href="home.html">Home</a></li>
      <li><a href="rlsdoc.html" >Release Document</a></li>
      <li><a href="dtadmp.html">Data Dump</a></li>
      <li><a href="facsetup.html">Facility Setup</a></li>
      <li><a href="dbuelem.html">DBU Elimination</a></li>
      <li><a href="contact.html">Contact us</a></li>
    </ul>
</div>

I want to put all the links (Home, Release Document etc) of div "nav" into a array so that I can iteratively use them. Please help me with the JavaScript code for this. Thanks in advance.

1
  • be more precise when you ask a question : do you need the text or the link of the "a" node ? Or do you want the node ? Commented Aug 11, 2011 at 10:52

5 Answers 5

3
document.getElementById("nav").getElementsByTagName("a")

this will return a node list that contains all "a" nodes

Sign up to request clarification or add additional context in comments.

Comments

0

This should do what you need with pure JavaScript:

window.onload = function() {
    var data = [];
    var oDiv = document.getElementById("nav");
    var links = oDiv.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++)
        data.push(links[i].innerHTML);
    alert(data.join("\n"));
};

Live test case.

Comments

0

We could use a combination of .querySelectorAll() to query the desired anchors and Array.prototype.forEach to iterate over those static element references.

var anchors = document.querySelectorAll('#linkselect a'),
    each    = [].forEach;

each.call( anchors, function( a ) {
    console.log( a );
});

Note: Both methods are not available in "old'ish" browsers, but are easily to create, lots of shims available.

2 Comments

This does not run in some browser, isn't it ?
@Jerome IE7 and below won't support the forEach for arrays, yep.
0

Try this.

Javascript

var items = [];
var anchors = document.getElementById("nav").getElementsByTagName("a");
for(var i = 0; i<anchors.length; i++){
    items.push(this.href);
}

jQuery

var items = [];
$("#nav a").each(function(){
    items.push(this.href);
});

2 Comments

@Shadow Wizard: yep. did not read properly. my bad :) but jquery is amazing and does all wonderful things
lol @[linked post] - nice one! Anyhow, while I agree jQuery is good and great it's not Command of God.. sometimes good old plain JavaScript will be better to use. :)
-1

jQuery:

$('#linkselect li a')

plain javascript:

document.getElementById('linkselect').getElementsByTagName("a")

1 Comment

It does not select all "a" nodes but "li" nodes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.