How to Manipulate the DOM Tree in JavaScript

In the last lesson, we introduced the concept of the DOM tree, and discussed how to select elements according to their ids, classes, names and element tags. And now, it is time to talk about how to manipulate the selected elements.

Altering the selected element

Let's start by talking about how to change a selected element.

Altering content

There are two properties available for altering the content of an element, innerHTML for all types of content, and textContent for textual content only.

  • innerHTML

The innerHTML property accesses the HTML content of an element. For example,

html
1<body>
2  <div id="parent">
3    <p id="first">Lorem ipsum dolor sit. . .</p>
4
5    <p id="second">
6      Quidem molestiae distinctio quae, <a href="">necessitatibus</a> deserunt
7      dignissimos. . .
8    </p>
9  </div>
10
11  <script src="index.js"></script>
12</body>
javascript
1let first = document.getElementById("first");
2console.log(first.innerHTML);
3
4let second = document.getElementById("second");
5console.log(second.innerHTML);

innerHTML

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉