<html>
<head></head>
<title></title>
<body>
<p id="para1">Hello John</p>
<p class="para2">Hello Stephen</p>
<p class="para2">Hello Edward</p>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Study</li>
</ul>
<script>
//Accessing all the child of the body
var child = document.body.children;
console.log(child);
//Adding new child in the body using two methods
var heading = document.createElement("h1");
var textNode = document.createTextNode("This is a new child.");
heading.appendChild(textNode);
console.log(heading); //confirm the creation of heading
document.body.appendChild(heading);
//Accessing firstChild and lastChild
var list = document.querySelector("ul");
console.log(list);
console.log(list.firstChild);
console.log(list.lastChild);
//Finding out the siblings
var firstSiblings = para1.nextElementSibling;
console.log(firstSiblings);
var secondSiblings = para1.nextElementSibling.nextElementSibling; //so on
console.log(secondSiblings);
//finding out the parents
console.log(list.parentNode);
</script>
</body>
</html>
Output:
//Accessing all the child of the body
Checkout the console
//Adding new child in the body using two methods
console: <h1></h1>
document: This is a new child.
//Accessing firstChild and lastChild
list: <ul></ul>
firstChild: #text (if no space <li>eat</li>)
lastChild: #text (if no space <li>study</li>)
//Finding out the siblings
First Sibling: <p class="para2">Hello Stephen</p>
Second Sibling: <p class="para2">Hello Edward</p>
//finding out the parents
ParentNode of the list : body
No comments:
Post a Comment