JavaScript DOM
Read and update HTML elements from JavaScript.
DOM Manipulation is one of the most exciting parts of JavaScript because it allows you to interact with and change web pages dynamically. You can update text, modify styles, create new elements, remove content, and respond to user actions without reloading the page.
What Is the DOM?
DOM stands for Document Object Model. When a browser loads an HTML page, it creates a structured representation of that page called the DOM.
HTML
<h1 id="title">Welcome</h1>
<p>This is a website.</p>Think of the DOM as a bridge between JavaScript and HTML.
Why Is DOM Manipulation Important?
- Change webpage content dynamically.
- Update styles and layouts.
- Show or hide elements.
- Create interactive user experiences.
- Respond to user actions.
Selecting Elements
Selecting by ID
JavaScript
let heading = document.getElementById("title");Using querySelector()
JavaScript
let heading = document.querySelector("#title");Changing Content
JavaScript
let heading = document.getElementById("title");
heading.textContent = "Hello JavaScript!";Before
HTML
<h1>Welcome</h1>After
HTML
<h1>Hello JavaScript!</h1>Changing Styles
JavaScript
let heading = document.getElementById("title");
heading.style.color = "blue";
heading.style.fontSize = "40px";Creating New Elements
JavaScript
let paragraph = document.createElement("p");
paragraph.textContent = "This paragraph was created with JavaScript.";
document.body.appendChild(paragraph);Removing Elements
JavaScript
let heading = document.getElementById("title");
heading.remove();Common DOM Methods
- getElementById(): select an element by ID
- querySelector(): select the first matching element
- querySelectorAll(): select multiple elements
- createElement(): create a new element
- appendChild(): add an element
- remove(): remove an element
Key Takeaways
- Dom is an important topic to understand.
- Start with small examples and practice one step at a time.
- Use the idea in simple projects so it becomes easier to remember.