Javascript DOM Methods List

The Document Object Model (DOM) is a programming interface for HTML and XML documents in JavaScript. It allows developers to access and manipulate the elements of a webpage using JavaScript methods. Here are some common DOM methods in JavaScript with examples.

getElementById()

Returns the element with the specified ID. For example, the following code will change the text of an element with the ID “myHeading”.

document.getElementById("myHeading").innerHTML = "New text";

getElementsByTagName()

Returns a collection of elements with the specified tag name. For example, the following code will change the color of all the <p> elements on a page.

var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.color = "blue";
}

getElementsByClassName()

Returns a collection of elements with the specified class name. For example, the following code will change the background color of all elements with the class “highlight”.

var elements = document.getElementsByClassName("highlight");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "yellow";
}

querySelector()

Returns the first element that matches a specified CSS selector. For example, the following code will change the font size of the first <p> element on a page.

var element = document.querySelector("p");
element.style.fontSize = "20px";

querySelectorAll()

Returns a collection of elements that match a specified CSS selector. For example, the following code will change the border color of all <li> elements in a <ul> element.

var elements = document.querySelectorAll("ul li");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.borderColor = "green";
}

createElement()

Creates a new element. For example, the following code will create a new <p> element and add it to the end of the body.

var newElement = document.createElement("p");
newElement.innerHTML = "This is a new element";
document.body.appendChild(newElement);

appendChild()

This method allows you to add a new element as a child of an existing element. For example, the following code will add a new <li> element with the text “Item 4” to the end of an existing <ul> element with the ID “myList”

var ul = document.getElementById("myList");
var li = document.createElement("li");
li.innerHTML = "Item 4";
ul.appendChild(li);

These are just a few examples of the many DOM methods available in JavaScript. The actual method used will depend on the specific requirements of the project.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories