DOM - Document Object Model (document.getElementById etc.)

 1) DOM:


What is the DOM?


The DOM stands for Document Object Model. It can simply be understood as a tree of nodes created by the browser. Each of these nodes has its own properties and methods which can be manipulated using JavaScript. The ability to manipulate the DOM is one of the most unique and useful abilities of JavaScript.

**

A "node", in this context, is simply an HTML element. The "DOM" is a tree structure that represents the HTML of the website, and every HTML element is a "node". 




















“document” is an object of the Document interface in the browser's Document Object Model (DOM). The Document interface represents an HTML or XML document that can be loaded in a web browser or processed by JavaScript code running in the browser.

The “document” object provides a way for JavaScript code to access and manipulate the contents of the web page represented by the Document interface. The document object has properties and methods that allow you to get and modify the HTML elements, styles, attributes, and content of the web page, as well as to add or remove elements dynamically.

The “Document” interface also defines other properties and methods that are not available directly on the document object but are inherited from its prototype chain. For example, the querySelector() and querySelectorAll() methods are defined on the Document interface and can be used to find HTML elements in the document using CSS selectors.




2) How to Select Elements in the DOM?

In order to be able to manipulate an element in the DOM, you have to select that particular element. There are 4 major ways of selecting elements:


1. getElementById(): The most common way to access an HTML element is to use the id of the element. The id is case-sensitive. For example, the 'master' and 'Master' are totally different ids. Once you have selected an element, you can add styles to the element, manipulate its attributes, and traverse to parent and child elements.

**Note

This is the best way to select an element.

<p id="master">I love Javascript</p>
<p id="master">I love HTML</p>
<script>
let masterEle1 = document.getElementById("master");
console.log(masterEle1);
</script>


Output in the browser
Output in the browser console. document.getElementById("master"), has grabbed the first element in the DOM with the id "master", rest with the same id will be ignored.


Note: In the JavaScript method document.getElementById(), the term "document" refers to the HTML document object that represents the web page currently loaded in the browser. The document object provides a way for JavaScript code to access and manipulate the contents of the web page, including its elements such as HTML tags, attributes, and content.


The getElementById() method is a function provided by the document object that allows JavaScript code to find a specific element in the web page by its unique ID attribute. When you call document.getElementById() and pass in the ID of an element as a parameter, the method will search the document for an element with that ID and return a reference to it, which you can then use to manipulate the element's properties and behaviour through JavaScript code.



 2. getElementsByClassName(): This method returns a collection of all elements (in array format) in the document with the specified class name.


<p class="master">I love Javascript</p>
<p class="master">I love React</p>
<p class="master">I want a Job</p>


<button id="btn">Click Me</button>
<script>
let btn = document.getElementById("btn");

btn.addEventListener("click", function master() {
let masterElements = document.getElementsByClassName("master");
masterElements[2].innerHTML = "I need a Job";
console.log(masterElements);
});

btn.addEventListener("click", function master() {
let masterElements = document.getElementsByClassName("master");
masterElements[1].innerHTML = "I love HTML";
console.log(masterElements);
});

btn.onclick = () => {
let masterElements = document.getElementsByClassName("master");
masterElements[0].innerHTML = "I love Java";
console.log(masterElements);
}
</script>


This is the output in the browser before clicking the click Me button.
This is the output after clicking the click Me button.
This is the output in the console after clicking the button. The collection of all the elements with the class "master" is printed in an array format.




3. getElementsByTagName(): This method accepts a tag name and returns all the elements of the specified tag name in the order in which they appear in the document.


<p>I love Javascript</p>
<p>I love React</p>
<p>I want a Job</p>
<button id="btn">Click Me</button>


<script>
let btn = document.getElementsByTagName("button");

btn[0].addEventListener("click", function master() {
let masterElements = document.getElementsByTagName("p");
let masterEle2 = masterElements[2].innerHTML = "I need a Job";
console.log(masterEle2);
});
</script>


This is the output in the browser before clicking the button.
This is the output in the browser after clicking the button.
document.getElementByTagName("p") has grabbed the p tag in index[2] (since we have mentioned only index 2) and printed its content in the browser console.



4. .querySelector() (CSS selector): This returns the first value that matches the selector it’s given. This method can accept all CSS style selectors, allowing it to select by tag, class, or ID.This method takes one argument, which is a CSS selector, and returns the first element that matches the selector.

** Note

This is the second best method to get HTML element after document.getElementByID().


<div id="master">I am a frontend developer</div>
<div id="master">I am a backend developer</div>
<script>
let masterElements = document.querySelector("#master");
console.log(masterElements);
</script>


In the document.querySelector(#master), we have selected the CSS id selector. Now that element will be selected that matches the id of the parameter and that is first in the DOM tree with that id.
Since both 1st and the 2nd div have same id (#master) but div with text "I am a frontend developer" is first in the DOM structure, therefore that div will be selected by the method document.querySelector(#master) and will be printed in the console as shown in the output.


5. .querySelectorAll(): This works similar to querySelector, which returns a node list collection of all matching elements (in an array).


<div id="master">I am a frontend developer</div>
<div id="master">I am a backend developer</div>
<script>
let masterElements = document.querySelectorAll("#master");
console.log(masterElements);
</script>










<p class="master">I am a frontend developer</p>
<p class="master">I am a backend developer</p>
<script>
let masterElements = document.querySelectorAll(".master");
console.log(masterElements);
</script>











3) How to Traverse the Document?


Everything in an HTML document is a node. Also the texts inside HTML elements are text nodes. With the HTML DOM, you can navigate the node tree and access nodes in the tree using node relationships (parent, child(ren), sibling(s) etc). New nodes can be created, and all nodes can be modified or deleted.


Points from DOM tree:


1. Every node has exactly one parent, except the top node (which has no parent).

2. A node can have more than one child.

3. Siblings are nodes with the same parent.


How to get the parent element, siblings of an element, and children of an element using the 

following node properties to achieve these things:


1. parentNode

2. childrenNodes

3. firstElementChild

4. lastElementChild

5. nextElementSibling

6. previousElementSibling


<div id="parent">
<div id="firstchild">I am the first child</div>
<p id="secondchild">I am the second child</p>
<h1>I am alive</h1>
<h2>Hello World</h2>
<p>I am the last child</p>
</div>


<script>
let lastElementChild = document.getElementById("parent").lastElementChild;
console.log(lastElementChild);//<p>I am the last child</p>


let result = document.getElementById("parent").children[3];
console.log(result);//<h2>Hello World</h2>


let secondchild = document.getElementById("secondchild");
console.log(secondchild.parentNode);//<div id="parent">...</div>
console.log(secondchild.nextElementSibling);//<h1>I am alive</h1>
console.log(secondchild.previousElementSibling);//<div id="firstchild">...</div>


let firstchild = document.getElementById("firstchild");
console.log(firstchild.previousElementSibling); // Null will be printed as there is no
sibling before "firstchild".
</script>






























4) Difference between innerHTML & innerText












innerHTML gives us the entire HTML element whereas innerText only gives us the text content of the HTML element.








Comments

Popular posts from this blog

Object.getOwnPropertyDescriptor & Object.defineProperty Methods.

Scope and Closures / Callback Hell