JavaScript HTML DOM Document
14 April 2025 | Category: JavaScript
The HTML DOM Document object represents the entire web page loaded in the browser. In JavaScript, the document
object is your gateway to access and modify the HTML content.
đź§ What is the document
Object?
- It’s part of the window object (
window.document
) - Represents the root of the HTML page
- Gives you access to everything on the page: tags, text, attributes, styles, etc.
🔑 Key Uses of document
Object
Task | Method/Property |
---|---|
Access an element by ID | document.getElementById() |
Access elements by class | document.getElementsByClassName() |
Access all elements by tag | document.getElementsByTagName() |
Access first matching CSS selector | document.querySelector() |
Access all matching CSS selectors | document.querySelectorAll() |
Change HTML content | .innerHTML |
Change text content | .textContent |
Modify attributes and styles | .setAttribute() , .style |
Create or delete elements | document.createElement() , .remove() |
đź§Ş Examples of Using the document
Object
âś… 1. Accessing Elements
<p id="demo">Hello!</p>
<script>
const el = document.getElementById("demo");
console.log(el.textContent); // Output: Hello!
</script>
âś… 2. Changing HTML Content
<p id="text">Old text</p>
<script>
document.getElementById("text").innerHTML = "New <strong>bold</strong> text";
</script>
âś… 3. Creating a New Element
<script>
const newEl = document.createElement("h2");
newEl.textContent = "This is a new heading!";
document.body.appendChild(newEl);
</script>
âś… 4. Changing Styles
<p id="colorText">Change my color</p>
<script>
const text = document.getElementById("colorText");
text.style.color = "blue";
text.style.fontWeight = "bold";
</script>
âś… 5. Changing Attributes
<a id="link" href="#">Click me</a>
<script>
const anchor = document.getElementById("link");
anchor.setAttribute("href", "https://www.google.com");
anchor.setAttribute("target", "_blank");
</script>
đź“‚ Other Useful document
Properties
Property | Description |
---|---|
document.title | Gets or sets the title of the page |
document.URL | Returns the URL of the document |
document.body | Access the <body> tag |
document.head | Access the <head> tag |
document.forms | All forms in the document |
document.images | All image tags in the document |
Example:
console.log(document.title); // Outputs: the page title
console.log(document.URL); // Outputs: the full page URL
âś… Conclusion
The document
object is one of the most powerful parts of JavaScript for:
- Accessing any part of the webpage
- Dynamically changing HTML content and CSS styles
- Creating, modifying, and deleting elements
- Handling events and forms