In this tutorial, we aim to understand how to select and manipulate the Document Object Model (DOM) elements using JavaScript. This is an essential skill as it enables you to make your web pages interactive and dynamic.
By the end of this tutorial, you will learn:
Prior experience with HTML and a basic understanding of JavaScript is beneficial for this tutorial.
The first step in manipulating DOM elements is to select the element. There are various methods to select DOM elements:
getElementById()
: Selects an element by its ID.getElementsByClassName()
: Selects elements by their class name.getElementsByTagName()
: Selects elements by their tag name.querySelector()
: Selects the first element that matches a specified CSS selector(s).querySelectorAll()
: Selects all elements that match a specified CSS selector(s).After selecting the DOM element, you can manipulate it in various ways:
innerHTML
, textContent
, or value
.style
.setAttribute()
.classList.add()
, classList.remove()
, or classList.toggle()
.// HTML
<div id="myDiv">Hello World!</div>
// JavaScript
let myElement = document.getElementById('myDiv');
console.log(myElement); // Logs the div element
In the above example, getElementById('myDiv')
selects the div with the ID 'myDiv'. The selected element is then logged to the console.
// HTML
<div id="myDiv">Hello World!</div>
// JavaScript
let myElement = document.getElementById('myDiv');
myElement.textContent = 'Hello Universe!';
In this example, textContent
changes the content of the selected div to 'Hello Universe!'.
In this tutorial, we covered how to select DOM elements using JavaScript and how to manipulate the selected elements. This included changing the content, style and attributes of elements, and adding or removing classes.
Next, you should learn about handling events in JavaScript, which often involves selecting and manipulating DOM elements.
Additional resources:
- MDN Web Docs - Document Object Model (DOM)
- JavaScript.info - DOM manipulation
Solution:
let testElement = document.getElementById('test');
testElement.textContent = 'I am the test element';
Solution:
let blueElements = document.getElementsByClassName('blue');
for(let i = 0; i < blueElements.length; i++) {
blueElements[i].style.color = 'blue';
}
Remember, practice makes perfect. So, keep experimenting and coding!