the problem with getting every node on a page is that you end up with a whole lot of stuff that you don't want (scripts, functions, etc). I don't know what you're trying to do, but maybe this comes closer...
I'm trying to learn how to run a basic search node by node to display the name of each node. Haven't tried your code yet. It's a little overwhelming for my level of knowledge in javascript. I made some modifications to what I had. Now, when clicking the "Show Nodes" button it just says "undefined". The error message in the web browser says "permission denied" at line 10
I would be interested to know why you want the node names and what your expected output is.
but anyway. Using document.write is useless for this purpose, because it will overwrite the contents of your file as soon as it is called, so the nodes you are trying to access will no longer exist. Use innerHTML instead.
Looking at the link you have posted you loop through all the elements with a "div" tag in your document (which happens to total one) then try to get the innerHTML of some element called childNodes. But childNodes is a collection (even if there is only one of them), so you have to loop through that as well.
Here's how I would do it, if for some weird reason I wanted to get the nodeNames of the childNodes (but like I say, I would be surprised if this is what you actually want...)
Code:
<html>
<body>
<head>
<script type="text/javascript" language="javascript">
function getNodes() {
var content = document.getElementsByTagName("div");
for (var i = 0; i < content.length; i++){
for (var a = 0; a < content[i].childNodes.length; a++){
document.getElementById("results").innerHTML+=content[i].childNodes[a].nodeName;
}
}
}
</script>
</head>
<div id="teams">
<h1>NFL Teams</h1>
<h2>NFC North</h2>
<p>Chicago Bears</p>
<p>Green Bay Packers</p>
<p>Minnesota Vikings</p>
<p>Detroit Lions</p>
<h2>NFC South</h2>
<p>New Orleans Saints</p>
<p>Atlanta Falcons</p>
<p>Carolina Panthers</p>
<p>Tampa Bay Buccannears</p>
<h2>NFC East</h2>
<p>Dallas Cowboys</p>
<p>Washington Redskins</p>
<p>Philadelphia Eagles</p>
<p>NY Giants</p>
<h2>NFC West</h2>
<p>San Francisco 49ers</p>
<p>Arizona Cardinals</p>
<p>Seattle Seahawks</p>
<p>St.Louis Rams</p>
</div>
<input type="button" value="Show Nodes" onclick="getNodes()">
<div id="results"></div>
</body>
</html>
Bookmarks