Document Object Model (DOM) - Complete Learning Page

Unit 2 JavaScript Learning Material

1. Why the DOM Matters

The DOM allows JavaScript to view an HTML document as a tree of objects instead of plain text. This makes webpages interactive.

ConceptDescription
HTMLStructure and content.
BOMBrowser Object Model (window).
DOMDocument Object Model (document).
window
└── document
    └── html elements

2. HTML Refresher & Browser Object Model

<!DOCTYPE html>
<html>
 <head><title>Tab</title></head>
 <body>
   <p>Hello Web!</p>
 </body>
</html>

Parent elements contain child elements. Attributes configure an element.

<a href="https://google.com">Here's a link!</a>

window Object

window.history.go(-1);

console.dir(navigator);

console.log(location.href);
location.href="https://google.com";

3. DOM Tree

document
└── html
    ├── head
    │   └── title
    └── body
        ├── h1
        └── div
            ├── p
            └── a
console.dir(document);

document.documentElement;
document.head;
document.body;

4. Selecting Elements

getElementById()

const ele=document.getElementById("one");

innerText vs innerHTML

msg.innerText="Updated text";

msg.innerHTML="<strong>Updated</strong>";
Use innerText for plain text. Use innerHTML only when HTML rendering is required. Never insert untrusted user input using innerHTML.

Other Selection Methods

document.getElementsByTagName("div");

document.getElementsByClassName("ele");

document.querySelector(".ele");

document.querySelectorAll(".myEle");

5. Manipulating Elements

Changing Style

title.style.color="red";
title.style.backgroundColor="yellow";

classList

item.classList.add("highlight");
item.classList.remove("highlight");
item.classList.toggle("highlight");

Attributes

el.getAttribute("data-row");
el.setAttribute("data-row","5");

Friends Table Example

function getData(el){
 let row=el.getAttribute("data-row");
 let name=el.getAttribute("data-name");
 message.innerHTML=`${name} is in row ${row}`;
}

6. Event Handling

Using this

<button onclick="message(this)">Button</button>

addEventListener()

const btns=document.querySelectorAll("button");

function output(){
 console.log(this.textContent);
}

btns.forEach(btn=>{
 btn.addEventListener("click",output);
});
addEventListener is preferred because it separates HTML and JavaScript and allows multiple handlers.

7. Creating Elements Dynamically

var li=document.createElement("li");
li.appendChild(document.createTextNode(text));
document.getElementById("sList").appendChild(li);

Pattern: Read input → Create element → Append element.

8. Putting Everything Together - Accordion

.myText{display:none;}
.myText.active{display:block;}

menus.forEach(el=>{
 el.addEventListener("click",()=>{
   openText.forEach(e=>e.classList.remove("active"));
   el.nextElementSibling.classList.toggle("active");
 });
});

Concepts Used

Chapter Summary