Introduction to Document Object Model - nodeType and nodeValue for nodes
Code for Displaying the nodeType property for nodes under the body section
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutorial</title>
</head>
<body>
This is some text
<a href="test.css">Click Here</a>
<p>This is a paragraph</p>
<h1>This is a h1</h1>
<h2>This is head3</h2>
<div>
hello how are you
</div>
<script>
const x = document.body.childNodes;
for(let i of x)
{
document.writeln(i.nodeType);
}
</script>
</body>
</html>
Output
Code for Displaying the nodeValue property for nodes under the body section
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutorial</title>
</head>
<body>
This is some text
<a href="test.css">Click Here</a>
<p>This is a paragraph</p>
<h1>This is a h1</h1>
<h2>This is head3</h2>
<div>
hello how are you
</div>
<script>
const x = document.body.childNodes;
for(let i of x)
{
document.writeln(i.nodeValue);
}
</script>
</body>
</html>
Output
Code for browsing the childnodes within another childnode. Consider
div as a childnode under the body section. We will traverse and print
the nodeName of all the childnodes under the div element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutorial</title>
</head>
<body>
This is some text
<a href="test.css">Click Here</a>
<p>This is a paragraph</p>
<h1>This is a h1</h1>
<h2>This is head3</h2>
<div>
hello how are you
<p>This is within the div element</p>
<h1>This is within div</h1>
<h2>This is within div a h2</h2>
</div>
<script>
const x = document.body.children;
for(let i of x)
{
if(i.nodeName.localeCompare('DIV')==0 && i.hasChildNodes)
{
const ch = i.childNodes;
for(let m of ch)
{
document.writeln(m.nodeName);
}
}
}
</script>
</body>
</html>
Output