On this page

Manipulating DOM elements

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Selecting Elements​

getElementById: This method gets an element by its ID.


let element = document.getElementById("myId");

getElementsByClassName: This method gets all elements with a specified class.


let elements = document.getElementsByClassName("myClass");

getElementsByTagName: This method gets all elements with a specified tag.


let elements = document.getElementsByTagName("div");

querySelector: This method gets the first element that matches a specified CSS selector(s) in the document.


let element = document.querySelector(".myClass");

querySelectorAll: This method gets all elements in the document that matches a specified CSS selector(s).


let elements = document.querySelectorAll(".myClass");

Changing Elements​

innerHTML: This property gets or sets the HTML content of an element.


element.innerHTML = "New content";

setAttribute: This method adds a new attribute or changes the value of an existing attribute on an element.


element.setAttribute("class", "newClass");

Adding Elements​

createElement: This method creates a new element node.


let newElement = document.createElement("div");

appendChild: This method adds a new child node to an element.


element.appendChild(newElement);

insertBefore: This method inserts a new child node before a specified child node.


element.insertBefore(newElement, childElement);

Removing Elements​

removeChild: This method removes a child node from an element.


element.removeChild(childElement);

remove: This method removes the element itself.


element.remove();

Remember, manipulating the DOM can cause the page to re-render, which can affect performance, so it’s best to minimize direct DOM manipulation where possible.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

DOM & Events

Next

Animations