What is the Document Object Model (DOM)?
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects, and it provides a way to access and manipulate them.
When a web page is loaded, the browser creates a Document Object Model of the page. The DOM is hierarchical and consists of a tree of nodes. The nodes can be HTML elements, attributes, text, or comments. The DOM provides methods and properties for accessing and manipulating these nodes.
getElementById() method. This method takes the ID of the element we want to select as its parameter and returns the element.
For example, let's say we have an HTML element with an ID of "my-element". We can select this element using the following code:
const myElement = document.getElementById("my-element")
myElement.textContent = "New content";
We can also change the HTML content of the element using the innerHTML property:
myElement.innerHTML = "<p>New content</p>";
In addition to changing the content of an element, we can also change its attributes. For example, we can change the value of the src attribute of an image element using the setAttribute() method:
const myImage = document.getElementById("my-image"); myImage.setAttribute("src", "new-image.jpg");
Another best practice is to cache the selected elements. Instead of selecting the same element multiple times, we should select it once and store it in a variable. This can improve performance by reducing the number of DOM queries our code needs to make.
Finally, we should be mindful of performance when manipulating the DOM. Manipulating the DOM can be a slow operation, especially if we're manipulating a large number of elements. It's important to be efficient with our code to minimize the impact on performance.