DOM in JavaScript – Simple Notes
What is DOM?
DOM stands for Document Object Model. It is a tree-like structure created by the browser when an
HTML page is loaded. JavaScript uses it to read or change the content, structure, or style of a
webpage.
DOM Tree Example:
For HTML like HelloWelcome!, the DOM tree looks like:
document → html → body → h1 → 'Hello', p → 'Welcome!'
Accessing Elements in DOM
1. getElementById(): [Link]("title")
2. getElementsByClassName(): [Link]("myClass")
3. getElementsByTagName(): [Link]("p")
4. querySelector(): [Link]("#title")
5. querySelectorAll(): [Link]("p")
Changing Content
Change text: [Link]("title").innerText = "Hello World!"
Change HTML: [Link]("title").innerHTML = "Hi"
Changing Style
[Link]("title").[Link] = "red"
Adding Elements
let newElement = [Link]("p");
[Link] = "New paragraph";
[Link](newElement);
Removing Elements
let element = [Link]("title");
[Link]();
Event Handling
HTML: Click me
JS: function sayHello() { alert("Hello!"); }
Summary Table
Feature Method
Get by ID getElementById()
Get by class getElementsByClassName()
Get by tag getElementsByTagName()
Query selector querySelector(), querySelectorAll()
Change content innerText, innerHTML
Change style .style
Add element createElement(), appendChild()
Remove element remove()