Problem accessing div elements
<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 开发者_Python百科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.
document.getElementById("nav").getElementsByTagName("a")
this will return a node list that contains all "a" nodes
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.
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.
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);
});
jQuery:
$('#linkselect li a')
plain javascript:
document.getElementById('linkselect').getElementsByTagName("a")
精彩评论