
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, you'll learn about creating, traversing, and removing nodes in the DOM using JavaScript. These operations are fundamental for dynamically manipulating web pages.
JavaScript provides several ways to create HTML elements dynamically. The most commonly used method is .
document.createElement("tagname"); // tagname can be any valid HTML tag
This method creates a new HTML element but does not add it to the DOM. You can set attributes and content using element properties and methods. To add the element to the DOM, use the method.
Example:
const newElement = document.createElement("div");
newElement.textContent = "Hello, World!";
document.body.appendChild(newElement);
Sometimes, you may not know the exact element you want to manipulate, but you know its relationship to other elements. JavaScript provides methods to traverse the DOM tree.
Example:
<ul class="subjects">
<li>Maths</li>
<li class="fav-subject">Science</li>
<li>English</li>
</ul>
<script>
const subjects = document.querySelector(".subjects");
console.log(subjects.firstElementChild); // First element of the list
console.log(subjects.lastElementChild); // Last element of the list
const favSub = document.querySelector(".fav-subject");
console.log(favSub.previousElementSibling); // Element before favorite subject
console.log(favSub.nextElementSibling); // Element after favorite subject
console.log(favSub.parentElement); // Parent of favorite subject (entire list)
</script>
Node Traversal Methods:
Removing elements from the DOM is another common task. For example, you might want to remove a login link once a user has logged in.
Example:
const favSub = document.querySelector(".fav-subject");
favSub.remove(); // Removes element from DOM
The method only removes the element from the DOM, but it remains in memory and can be re-added if needed.
Understanding how to create, traverse, and remove nodes is essential for building dynamic and interactive web applications. These operations allow you to modify the structure and content of web pages in response to user actions or other events.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.