The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.
Refer:
https://www.w3schools.com/js/img_htmltree_800.svg
Core Concepts
- The DOM Tree: The HTML document becomes a hierarchy of nodes.
- Nodes: Everything is a node (elements, text, comments).
-
Elements: HTML tags(like or
)converted into JavaScript objects.
1. Selecting Elements
To manipulate an element, you must first find it in the DOM tree.
- document.getElementById('id') — Finds a single element by its unique ID.
- document.getElementsByClassName('class') — Returns a live collection of elements with that class.
- document.getElementsByTagName('tag') — Returns a live collection of elements with that tag name.
- document.querySelector('selector') — Returns the first element matching a CSS selector.
- document.querySelectorAll('selector') — Returns a static NodeList of all elements matching a CSS selector.
2. Modifying Content and Attributes
Once selected, you can alter the text, HTML contents, or attributes of an element.
- element.textContent — Gets or sets the text inside an element (ignores HTML tags).
- element.innerHTML — Gets or sets the HTML markup inside an element.
- element.setAttribute('attr', 'value') — Adds or updates an attribute (e.g., src, href).
- element.getAttribute('attr') — Retrieves the value of a specified attribute.
- element.removeAttribute('attr') — Removes an attribute from the element.
Quick Example
`
<h1 id="welcome">
welcome.....!!!!!
</h1>
<button onclick="getTxt()"> change the inside </button>
<script>
function getTxt() {
const ele = document.getElementById("welcome");
if (ele.innerText == "welcome.....!!!!!") {
ele.innerText = "ViNo";
} else {
ele.innerText = "welcome.....!!!!!"
}
console.log(ele.innerText);
}
</script>
`
Top comments (0)