Understanding Family Structure in the DOM API in JavaScript


In the Document Object Model (DOM) in JavaScript, family structure refers to the hierarchical relationship between HTML elements on a web page. The DOM tree represents the structure of an HTML document as a tree-like structure, where each node in the tree represents an element, attribute, or piece of text in the document. The family structure of DOM is also known as the parent-child relationship.

Every element in the DOM tree has a parent element, except for the root element which is the topmost element in the tree. The parent element is the element that contains other child elements within it. The child elements, on the other hand, are the elements that are contained within a parent element.

The family structure of DOM allows developers to traverse and manipulate the structure of HTML elements on a web page. Developers can access and manipulate elements by selecting them based on their position in the DOM tree using methods such as getElementById, getElementsByClassName, and querySelector.

Furthermore, developers can also manipulate the family structure of DOM by adding, removing, or moving elements within the tree using methods such as appendChild, insertBefore, and removeChild.

Overall, the family structure of DOM is an essential concept for web development and provides a powerful tool for developers to create dynamic and interactive web pages. Understanding the parent-child relationship between HTML elements is crucial for manipulating the structure of a web page using the DOM API in JavaScript.

family structure


Example

Source Code

<html lang="en">
  <head>
    <title>Tutor Joes</title>
  </head>
  <body>
    <ul>
      <li>C</li>
      <li>C++</li>
      <li>Java</li>
    </ul>
    <script src="107_H_node.js"></script>
  </body>
</html>

JavaScript File

//HTMLCollection
/*
let li = document.getElementsByTagName("li");
console.log(li);
console.log(li.length);
let element = document.createElement("li");
element.innerHTML = "JavaScript";
li[0].parentNode.appendChild(element);
console.log(li);
console.log(li.length);
for (let i = 0; i < li.length; i++) {
  li[i].style.color = "orange";
}
*/

let li = document.querySelectorAll("li");
console.log(li);
console.log(li.length);
let element = document.createElement("li");
element.innerHTML = "JavaScript";
li[0].parentNode.appendChild(element);
console.log(li);
console.log(li.length);

li.forEach((element) => {
  element.style.color = "orange";
});

li = document.querySelectorAll("li");
console.log(li);
console.log(li.length);

List of Programs


JS Practical Questions & Answers


JS Practical Project