What is the DOM?
For instance, let's take a look at a simple example:
// get the element with id "demo" var elem = document.getElementById("demo"); // change the text of that element elem.innerHTML = "Hello, World!";
getElementById method to find an HTML element with the id "demo". Then, it changes the content of this element using the
Understanding the DOM Tree
document is the root node, from which all other nodes branch off. Element nodes represent HTML elements (
<div>, etc.), and text nodes contain the text inside those elements.
Here's a simple example of how a DOM tree might look for a basic HTML document:
<!DOCTYPE html> <html> <body> <h1>My Heading</h1> <p>My paragraph.</p> </body> </html>
The corresponding DOM tree would look like this:
document └── html ├── head └── body ├── h1 │ └── "My Heading" └── p └── "My paragraph."
Traversing the DOM
parentNode: This property returns the parent node of a specified node.
previousSibling: These properties return the next and previous sibling of a node, respectively.
lastChild: These properties return the first and last child of a node, respectively.
Manipulating the DOM
- Changing the content of HTML elements
- Changing the attributes of HTML elements
- Changing the style (CSS) of HTML elements
- Adding and deleting HTML elements
Here's a simple example of changing the content of an HTML element:
document.getElementById("demo").innerHTML = "Hello, World!";
And here's an example of changing an element's style:
document.getElementById("demo").style.color = "red";
Q: What is the difference between the DOM and the HTML source code?
Q: What's the difference between
innerHTML returns or sets the HTML content inside an element (including any HTML tags).
textContent returns or sets only the text content, without any HTML tags.
Free money-back guarantee
Unlimited access to all platform courses
100's of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Mayank Sharma wrote? Thank them for their work by sharing it on social media.
No comments so far
Leave a question/feedback and someone will get back to you