DOM with JS - ByteScout

DOM with JS

DOM with JS

What is DOM?

The terminology DOM represents the Document Object Model of a page. The World Wide Web Consortium separates DOM into three parts:

  1. HTML DOM is the standard model for HTML documents.
  2. XML DOM is the standard model for XML documents.
  3. Core DOM is the standard model for all document types.

The browser helps create a DOM of a web page when it loads. DOM considers every HTML tag and the text inside it as objects. JavaScript can access all these objects and their children to manipulate and modify the web page. Following are some important manipulations a developer can perform using JavaScript and accessing the Object Model:

  1. Modify HTML elements
  2. Modify HTML attributes
  3. Modify CSS styles
  4. Add HTML elements and attributes
  5. Remove HTML elements and attributes
  6. Add HTML elements
  7. Add reaction to DOM events

Manipulating DOM using JavaScript

The developers can use the Javascript DOM API to manipulate any HTML document. This opportunity to modify DOM by creating, removing, modifying, and styling the elements provides user interactivity with browsers. JavaScript helps manipulate the DOM since DOM uses an object-oriented approach. Developers can work with the properties and methods available to modify the DOM according to their requirements. Following are some of the primary techniques to manipulate the DOM.

Select DOM Elements

The DOM programming interface provides properties and methods for every object. The “property” is a value that a developer can change or set, and the “method” is the action a developer can perform on an object. Moreover, the developers can use various selectors to select DOM elements. These selectors represent document object methods to pull the required elements. Following are some of the JavaScript DOM selectors:

getElementById()

This selector chooses the elements based on their identification name and returns the first matched element. It uses the most common way of accessing a tag.

Example

Following is an example of selecting a DOM element using the getElementById method.

<html>
<body>
<p id="sample"></p>
<script>
document.getElementById("sample").innerHTML = "Hello World!";
</script>
</body>
</html>

In this example, “getElementById” is a method and “innerHTML” is a property. Here, the method helps find the required element, and the property helps get or set the element’s content. In this example, the selector uses the id of a <p> tag having the name “sample” and changes the content of this element with “Hello World!”.

getElementByClassName()

This selector chooses the elements based on their class names. It returns all the tags that match the given class name.

Example

Following is an example of selecting a DOM element using the getElementByClassName method.

<html>
<body>
<div id="Sample">
 <p class="child">I am a paragraph.</p>
 <p class="child">I am a paragraph.</p>
 <p class="child">I am a paragraph.</p>
</div>
<p id="demo"></p>
<script>
const element = document.getElementById("Sample");
const nodes = element.getElementsByClassName("child");
document.getElementById("demo").innerHTML = nodes.length;
</script>
</body>
</html>

The above example uses the getElementByClassName method to identify the total number of elements having the class name “child” and exist in the div named “Sample”. This example also uses the getElementById method to identify the specific div.

getElementByTagName()

This selector chooses the elements based on their tag names. This method returns all the tags having a specific tag name.

Example

Following is an example of selecting a DOM element using the getElementByTagName method.

<html>
<body>
<p>An unordered list:</p>
<ul>
 <li>Coffee</li>
 <li>Tea</li>
 <li>Milk</li>
</ul>
<p>The second element is:</p>
<p id="Sample"></p>
<script>
const collection = document.getElementsByTagName("li");
document.getElementById("Sample").innerHTML = collection[1].innerHTML;
</script>
</body>
</html>

The above example uses getElementByTagName method to identify a specific element. In this case, it returns the second element from a collection based on the tag name “li” in the paragraph id “Sample”.

querySelector()

This method uses a specific CSS selector in the document to match the element. This selector returns the first element to compare with the given CSS selector.

Example

Following is an example of selecting a DOM element using the querySelector method.

<html>
<body>
<p class="example">First.</p>
<p class="example">Second.</p>
<script>
document.querySelector(".example").style.backgroundColor = "grey";
</script>
</body>
</html>

The above example uses the querySelector method to identify the first element matching with a CSS selector. In this case, the selector identifies the first element having class “example” and adds a background color to it. This method throws a syntax error exception if the provided selector is not valid.

querySelectorAll()

This method uses a specific CSS selector in the document. This selector returns all the elements in the DOM matching the provided CSS selector.

Example

Following is an example of selecting DOM elements using the querySelectorAll method.

<html>
<body>
<h2 class="example">First</h2>
<p class="example">Second.</p>
<script>
const nodeList = document.querySelectorAll(".example");
for (let i = 0; i < nodeList.length; i++) {
 nodeList[i].style.backgroundColor = "grey";
}
</script>
</body>
</html>

The above example uses the querySelectorAll method to identify all element matching with a CSS selector. In this case, the selector identifies all the elements having class “example” and adds a background color to it. This method also throws a syntax error exception if the provided selector is not valid.

Traverse the DOM Elements

The Document Object Model consists of a collection of nodes and elements. Therefore, these nodes have a parent, child, and sibling relationship. The developers can use relationship properties such as the child node, first child, next sibling, and last child to traverse up and down in the DOM to modify the required nodes.

Example

<div>
   <ul class="list">
       <li  class="list-item">first child</li>
       <li class="list-item">second child</li>
   </ul>
</div>
<script>
 let list = document.querySelector("ul");
 let parentElement =list.parentNode;
 console.log(parentElement);
</script>

The above example uses the querySelector method to return the element using the CSS selector “ul”. Moreover, it uses parentNode to traverse up in the DOM tree. The console returns the div tag as the parent element in this example. The developers can use this technique to add styling and modify the document according to their requirements.

Add and Remove Elements from DOM

The developers can use JavaScript to manipulate DOM by adding and removing specific elements.

Add Elements In DOM

The users must first create an element to add to the DOM. For this purpose, the users must create the element node and append that to an already existing one.

Example
<html>
<body>
<div id="div1">
<p id="p1">First.</p>
<p id="p2">Second.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("Third.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>

In this example, the createElement() creates a new paragraph tag, and the createTextNode() creates a text node and adds text to it. The next step is to append the text node to the paragraph element. Therefore, the appendChild() method appends the text node to the paragraph element. Finally, using the appendChild() again appends the newly created element to the existing one by finding it using the getElementById selector.

Remove Elements From DOM

The users can also remove an existing element from the DOM. For this purpose, the users can use the remove() method to delete a tag or a node from the document.

Example
<html>
<body>
<p id="demo">Click to remove.</p>
<button onclick="myFunction()">Remove</button>
<script>
function myFunction() {
 const element = document.getElementById("demo");
 element.remove();
}
</script>
</body>
</html>

Using this example, the developers can delete any element from the DOM by searching the tag first using the getElementById() method and then delete it using the remove() function. Moreover, there is a method removeChild() to delete a single child or all of them from a collection. The users can also add a removed node into the same document using appendChild() or insertBefore() methods. Furthermore, the users can change the behaviour of a page using JavaScript and manipulate the DOM according to the required scenarios.

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next