JavaScript allows you to manipulate HTML elements in a number of ways. This can be useful for tasks such as changing the content or style of an element or even adding or deleting elements from the DOM (Document Object Model).
Getting Elements
There are several ways to get a reference to an HTML element in JavaScript. One of the most common ways is to use the getElementById method:
let element = document.getElementById("some-id");
This method searches the DOM for an element with the specified ID and returns a reference to it. If no such element is found, it returns null.
You can also use the getElementsByTagName and getElementsByClassName methods to get a list of elements with a specific tag name or class name:
let elements = document.getElementsByTagName("p"); // gets all <p> elements
let elements = document.getElementsByClassName("some-class"); // gets all elements with class "some-class"
These methods return a collection of elements, which can be accessed like an array:
let firstElement = elements[0]; let secondElement = elements[1];
Setting Element Content
Once you have a reference to an element, you can use the innerHTML property to set its content:
element.innerHTML = "Some new content";
This will replace the element’s current content with the specified content.
Adding Elements
To add a new element to the DOM, you can use the createElement method:
let newElement = document.createElement("p"); // creates a new <p> element
You can then set the content of the element and append it to the DOM:
newElement.innerHTML = "Some new content"; document.body.appendChild(newElement); // adds the new element to the end of the <body> element
Deleting Elements
To delete an element from the DOM, you can use the removeChild method:
let parentElement = element.parentNode; // gets the parent element of the element to be deleted parentElement.removeChild(element); // removes the element from the DOM
Traversing the DOM
Once you have a reference to an element, you can use its properties to navigate the DOM and get references to other elements.
For example, the parentNode property returns a reference to the element’s parent element:
let parentElement = element.parentNode;
The childNodes property returns a collection of the element’s child nodes:
let childNodes = element.childNodes;
And the nextSibling and previousSibling properties return references to the element’s next and previous siblings, respectively:
let nextSibling = element.nextSibling; let previousSibling = element.previousSibling;
These properties can be useful for tasks such as traversing the DOM and finding specific elements.
Here are a few additional things you might find helpful:
Selecting Elements using Query Selectors
In addition to the methods mentioned above, you can also use query selectors to select elements. Query selectors allow you to select elements using CSS-style selectors, such as #some-id to select an element with a specific ID or .some-class to select all elements with a specific class.
To use query selectors, you can use the querySelector and querySelectorAll methods:
let element = document.querySelector("#some-id"); // selects the first element with the ID "some-id"
let elements = document.querySelectorAll(".some-class"); // selects all elements with the class "some-class"
Setting Element Attributes
You can use the setAttribute method to set the value of an element’s attribute:
element.setAttribute("href", "https://example.com"); // sets the "href" attribute of the element
You can also use the attribute name as a property to set the attribute value:
element.href = "https://example.com"; // sets the "href" attribute of the element
Setting Element Styles
You can use the style property to set the style of an element:
element.style.color = "red"; // sets the color of the element to red element.style.fontSize = "20px"; // sets the font size of the element to 20px
You can also set multiple styles at once by assigning an object to the style property:
element.style = {
color: "red",
fontSize: "20px"
};
Setting CSS Styles
You can use the style property to set the style of an element, as we saw in the previous section. This allows you to set individual CSS styles, such as the element’s color or font size.
Another option is to use the className property to set the element’s class, which can be used to apply a set of styles defined in a CSS stylesheet:
element.className = "some-class"; // sets the class of the element to "some-class"
You can also use the classList property to add or remove classes from the element:
element.classList.add("some-class"); // adds the "some-class" class to the element
element.classList.remove("some-class"); // removes the "some-class" class from the element
Getting CSS Styles
You can use the getComputedStyle method to get the computed style of an element, which represents the final styles that are applied to the element:
let computedStyle = window.getComputedStyle(element);
You can then use the getPropertyValue method to get the value of a specific style:
let color = computedStyle.getPropertyValue("color"); // gets the value of the "color" style
Modifying Styles with CSS Classes
A common approach to modifying styles is to define a set of CSS classes in a stylesheet, and then toggle these classes on and off as needed. This allows you to keep your styles separate from your JavaScript code, making it easier to maintain and modify your styles over time.
For example, you might define a set of CSS classes in your stylesheet:
.highlight {
background-color: yellow;
font-weight: bold;
}
.hidden {
display: none;
}
Then, you can use JavaScript to toggle these classes on and off as needed:
element.classList.add("highlight"); // adds the "highlight" class to the element
element.classList.remove("hidden"); // removes the "hidden" class from the element
Some Examples
Here are a few examples of how you might use the techniques described in this tutorial in a real-life scenario:
- Changing the content of a webpage: You might use the
innerHTMLproperty to change the content of an element on a webpage. For example, you might have a page with a “Click here” button that, when clicked, displays a message below the button. You could use JavaScript to change the button’sinnerHTMLto “Close” and the message’sinnerHTMLto “The button has been clicked.”
let button = document.getElementById("button");
let message = document.getElementById("message");
button.addEventListener("click", function() {
if (button.innerHTML === "Click here") {
button.innerHTML = "Close";
message.innerHTML = "The button has been clicked.";
} else {
button.innerHTML = "Click here";
message.innerHTML = "";
}
});
- Adding and deleting elements from a list: You might use the
createElementandappendChildmethods to add new elements to a list, and theremoveChildmethod to delete elements from the list. For example, you might have a page with a list of items that users can add to or remove from. You could use JavaScript to add a new item to the list when the user clicks a “Add” button and delete an item when the user clicks a “Delete” button.
let list = document.getElementById("list");
let addButton = document.getElementById("add-button");
addButton.addEventListener("click", function() {
let newItem = document.createElement("li");
newItem.innerHTML = "New item";
list.appendChild(newItem);
});
list.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
let item = event.target;
let parent = item.parentNode;
parent.removeChild(item);
}
});
- Traversing the DOM to find elements: You might use the
parentNode,childNodes,nextSibling, andpreviousSiblingproperties to traverse the DOM and find specific elements. For example, you might have a page with a complex layout that includes several nested elements, and you need to find a specific element that is several levels deep in the DOM. You could use these properties to navigate the DOM and find the element you need.
let element = document.getElementById("some-element");
// Find the parent element of the element
let parent = element.parentNode;
// Find the first child element of the element
let child = element.childNodes[0];
// Find the next sibling element of the element
let nextSibling = element.nextSibling;
// Find the previous sibling element of the element
let previousSibling = element.previousSibling;
- Modifying element styles: You might use the
styleproperty or theclassNameandclassListproperties to modify the styles of elements on a webpage. For example, you might have a page with a set of buttons, and you want to change the background color of the button when the user hovers over it. You could use thestyleproperty to set thebackground-colorstyle when the user’s mouse enters the button and reset it when the mouse leaves. Alternatively, you could define a set of CSS classes in a stylesheet and use theclassListproperty to toggle the classes on and off as needed.
Using style property:
let button = document.getElementById("button");
button.addEventListener("mouseenter", function() {
button.style.backgroundColor = "yellow";
});
button.addEventListener("mouseleave", function() {
button.style.backgroundColor = "";
});
Using classList property:
.highlight {
background-color: yellow;
font-weight: bold;
}
.hidden {
display: none;
}
let button = document.getElementById("button");
button.addEventListener("mouseenter", function() {
button.classList.add("highlight");
});
button.addEventListener("mouseleave", function() {
button.classList.remove("highlight");
});
Practice Exercise
Here are some practice exercises you can try to test your understanding of manipulating DOM elements using JavaScript:
- Create a page with a list of items, and allow the user to add new items to the list by typing in an input field and pressing a “Add” button.
- Create a page with a table of data, and allow the user to sort the table by clicking the table headers.
- Create a page with a set of tabs, and allow the user to switch between the tabs by clicking them.
- Modify the styles of a page based on the user’s preferences. For example, create a page with a set of buttons that allow the user to change the font size, color scheme, and other styles.
- Create a page with a set of images, and allow the user to view a larger version of the image by clicking on it.
- Create a page with a set of “accordion” sections, where each section can be expanded or collapsed by clicking a header.
- Create a page with a set of “tabbed” sections, where each section can be displayed by clicking a tab.
- Create a page with a form that validates the user input and displays error messages when necessary.
I hope these exercises help you practice your skills! Let me know if you have any questions.
In this tutorial, we learned how to manipulate HTML elements in JavaScript using methods such as getElementById, getElementsByTagName, and getElementsByClassName. We also learned how to set the content of an element, add new elements to the DOM, delete elements from the DOM, and traverse the DOM using properties such as parentNode, childNodes, nextSibling, and previousSibling.
We hope this helps! Please let us know if you have any questions or confusion, and feel free to share your review or feedback. Your comments and contributions help us improve and provide better content for our community.
