- Courses
- đ»Programming Languages
- đJavaScript
- DOM & Events
- Manipulating DOM elements
On this page
Manipulating DOM elements
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!
Previous
DOM & Events
Next
Animations
- Selecting Elements
- Changing Elements
- Adding Elements
- Removing Elements
