Reputation: 41
I am new to JavaScript and when I was playing around with the DOM model I was getting confused when I wanted to display all nodeName
s from the HTML childNodes
.
There is a nodeName
called #text when i have an head
tag and when I delete the complete head
tag there is the normal HEAD and BODY nodeName
.
What means the #text nodeName
especally when I have a head
tag?
Here is my code:
<html>
<head>
</head>
<body>
<p id="p1">SOME TEXT</p>
<button type="button" onclick="javascript:changeNode()">Click </button>
<script type="text/javascript">
function changeNode() {
var htmlNode = document.documentElement;
var anzahl = htmlNode.childNodes.length;
var html_text = "<p>";
for(var i = 0;i<anzahl;i++){
html_text += " " + htmlNode.childNodes[i].nodeName +";";
}
html_text += "</p>";
document.getElementById("p1").innerHTML = html_text;
}
</script>
</body>
</html>
The output of it is (with the head
tag):
HEAD; #text; BODY;
The output of it is (without the head
tag):
HEAD; BODY;
Upvotes: 3
Views: 1538
Reputation: 90
Whitespace inside elements is considered as #text, and text is considered as nodes. Remove the space between </head>
& <body>
tag like below:
<html>
<head></head><body>
<p id="p1">SOME TEXT</p>
<button type="button" onclick="javascript:changeNode()">Click </button>
</body>
This will give you the output HEAD,BODY
Upvotes: 1
Reputation: 68383
What means the #text nodeName especally when i have a head tag.
these are the empty line breaks that you have unintentionally introduced in your markup.
Use children
instead of childNodes
if you don't want to include text nodes.
Upvotes: 3