Introduction to Document Object Model - JavaScript
Code for displaying the nodeName of all nodes within the body tag of a webpage
and changing the textcontent for certain childnodes using JavaScript
<!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
</div>
<script>
//printing all the childnodes in body of a document
const x = document.body.childNodes;
for(let i of x)
{
document.writeln(i.nodeName)
}
document.body.childNodes[1].textContent="Lets change it";
</script>
</body>
</html>
Output
Code for traversing through all the childnodes of the head element and printing the
text content in the title node
<!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>
<script>
const x = document.head.childNodes;
for(let i of x)
{
if(i.nodeName.localeCompare("TITLE")==0)
{
document.writeln(i.textContent);
}
}
</script>
</body>
</html>
Output
Code for manipulating CSS using Javascript DOM
<!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>
<a href="test.css">Click Here</a>
<p>This is a paragraph</p>
<h1>This is a h1</h1>
<script>
document.documentElement.style.background="bisque";
document.body.style.color="red";
</script>
</body>
</html>
Output