The Document Object Model [Part 3]

The Document Object Model [Part 3]

The Document Object Model or DOM is a JavaScript representation of a HTML document. Each element (or node) is connected to its children and its parent element in a tree.

Take the following HTML document:

<html>
  <head>
    <title>The DOM</title>
    <link href="./styles.css">
  </head>
  <body>
    <h1>The Document Object Model</h1>
    <img src="./dom.jpg" alt="A visual representation of the DOM" />
  </body>
</html>
        

We can represent the DOM for this HTML document visually like so:

Retrieving Elements From The DOM

We can access the elements using the document object. It has several methods for retrieving DOM nodes. Let’s look at the more common ones:

document.getElementById('title'); // retrieves an element with the given ID

document.getElementsByClassName('selected'); // retrieves all elements with the given class

document.querySelector('#title'); // retrieves the first item that matches the selector

document.querySelectorAll('.selected') // retrieves all elements that match the selector
        

The most efficient way of selecting an element is by ID, so you should favor using IDs on your DOM elements where possible.

Storing Elements in Variables

Once you have retrieved the elements you want to work with, you should store them in variables to modify them without having to re-retrieve them from the DOM. Remember: DOM traversal is relatively inefficient and should be done as little as possible.

Choosing appropriate names for the variables in which you store your DOM nodes is important. It would be best if you favored descriptive names over shorter names. btn might make sense if there’s only one button in your project, but submitButton is a lot more descriptive and helps to give context to the element.

DOM Manipulation

Now that you can effectively retrieve DOM elements, let’s look at how we can modify them.

const paragraph = document.querySelector('p'); // retrive the first <p /> from the document

paragraph.textContent = 'Hello World!'; // set the contents of the element

paragraph.style.color = 'red'; // style the element

paragraph.remove(); // remove the element

document.body.appendChild(paragraph); // insert the element back into the DOM as the last child of the <body> tag 
        

Essentially, it’s as simple as that. Once you have retrieved an element, you can modify it however you want. You just need to know the appropriate property or method.

Conclusion

In this article, we’ve covered accessing and updating the DOM by retrieving elements and updating their attributes to change how a webpage looks dynamically.

Previous Parts:

Part 1: https://www.dhirubhai.net/pulse/setting-up-your-project-use-javascript-part-1-akash-gadhiya-nts4f/

Part 2: https://www.dhirubhai.net/pulse/taking-up-level-hot-reloading-part-2-akash-gadhiya-pwwyf/

要查看或添加评论,请登录

Akash G.的更多文章

社区洞察

其他会员也浏览了