JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript HTML DOM Document

14 April 2025 | Category:

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

TaskMethod/Property
Access an element by IDdocument.getElementById()
Access elements by classdocument.getElementsByClassName()
Access all elements by tagdocument.getElementsByTagName()
Access first matching CSS selectordocument.querySelector()
Access all matching CSS selectorsdocument.querySelectorAll()
Change HTML content.innerHTML
Change text content.textContent
Modify attributes and styles.setAttribute(), .style
Create or delete elementsdocument.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

PropertyDescription
document.titleGets or sets the title of the page
document.URLReturns the URL of the document
document.bodyAccess the <body> tag
document.headAccess the <head> tag
document.formsAll forms in the document
document.imagesAll 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