The DOM represents an HTML or XML document as a tree - like structure. Each node in the tree can be accessed and manipulated using JavaScript. Nodes can be elements (such as <div>
, <p>
), text nodes, or attribute nodes. When we talk about selecting and modifying elements in the DOM, we are essentially finding specific nodes in the tree and changing their properties or content.
The getElementById
method is used to select a single element with a specific ID.
// HTML
// <div id="myDiv">This is a div</div>
const myDiv = document.getElementById('myDiv');
console.log(myDiv);
In this example, we are selecting the <div>
element with the ID myDiv
.
The getElementsByClassName
method returns a collection of elements with a specific class name.
// HTML
// <p class="myClass">Paragraph 1</p>
// <p class="myClass">Paragraph 2</p>
const paragraphs = document.getElementsByClassName('myClass');
for (let i = 0; i < paragraphs.length; i++) {
console.log(paragraphs[i]);
}
The getElementsByClassName
method returns an HTMLCollection, which is a live collection of elements.
The getElementsByTagName
method returns a collection of elements with a specific tag name.
// HTML
// <li>Item 1</li>
// <li>Item 2</li>
const listItems = document.getElementsByTagName('li');
for (let i = 0; i < listItems.length; i++) {
console.log(listItems[i]);
}
This method also returns an HTMLCollection.
The querySelector
and querySelectorAll
methods allow you to select elements using CSS selectors.
// HTML
// <div class="container">
// <p>Some text</p>
// </div>
// Select the first element that matches the selector
const firstParagraph = document.querySelector('.container p');
console.log(firstParagraph);
// Select all elements that match the selector
const allParagraphs = document.querySelectorAll('.container p');
allParagraphs.forEach(paragraph => {
console.log(paragraph);
});
The querySelector
method returns the first element that matches the selector, while querySelectorAll
returns a static NodeList of all matching elements.
The textContent
property is used to change the text content of an element.
// HTML
// <p id="myParagraph">Old text</p>
const myParagraph = document.getElementById('myParagraph');
myParagraph.textContent = 'New text';
The innerHTML
property is used to change the HTML content of an element.
// HTML
// <div id="myDiv"></div>
const myDiv = document.getElementById('myDiv');
myDiv.innerHTML = '<h2>New heading</h2>';
The setAttribute
and getAttribute
methods are used to modify and get attributes of an element.
// HTML
// <img id="myImage" src="oldImage.jpg">
const myImage = document.getElementById('myImage');
myImage.setAttribute('src', 'newImage.jpg');
const newSrc = myImage.getAttribute('src');
console.log(newSrc);
The style
property is used to change the inline styles of an element.
// HTML
// <p id="myParagraph">Some text</p>
const myParagraph = document.getElementById('myParagraph');
myParagraph.style.color = 'red';
myParagraph.style.fontSize = '20px';
// HTML
// <button id="myButton">Click me</button>
// <div id="myDiv">Initial content</div>
const myButton = document.getElementById('myButton');
const myDiv = document.getElementById('myDiv');
myButton.addEventListener('click', function () {
myDiv.textContent = 'Content changed after click';
});
// HTML
// <ul id="myList"></ul>
// <button id="addItem">Add Item</button>
const myList = document.getElementById('myList');
const addItemButton = document.getElementById('addItem');
addItemButton.addEventListener('click', function () {
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
myList.appendChild(newItem);
});
// HTML
// <p id="myParagraph">Some text</p>
// <button id="changeStyle">Change Style</button>
// CSS
// .highlight {
// color: blue;
// font - weight: bold;
// }
const myParagraph = document.getElementById('myParagraph');
const changeStyleButton = document.getElementById('changeStyle');
changeStyleButton.addEventListener('click', function () {
myParagraph.classList.add('highlight');
});
const myElement = document.getElementById('nonExistentElement');
if (myElement) {
myElement.textContent = 'Element exists';
} else {
console.log('Element not found');
}
JavaScript DOM manipulation for selecting and modifying elements is a crucial skill for web developers. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can create highly interactive and dynamic web applications. Remember to use the appropriate selection methods based on your requirements and follow best practices to keep your code clean and maintainable.