Document Object Model is a very powerful tool and also very important topic for javascript programmers.
The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents. The nodes of every document are organized in a tree structure, called the DOM tree.

querySelector() and querySelectorAll():
<div id="test">
<ul>
<li>c++</li>
<li>java</li>
<li>js</li>
<li>php</li>
</ul>
</div>
querySelector(css selector) returns one element (the first occurrence). We use the same CSS style selector as a argument for the function. we should use this function, if our target element is not more than one:
var test = document.querySelector("#test ul li:nth-child(2)");
console.log(test.textContent); // java
querySelectorAll(css selector) returns an array of elements. We should use this function if our target element is more than one. Also we have to access the returned element in array style.
var test = document.querySelectorAll("#test ul li");
console.log(test[2].textContent); // js
getElementById():
This function tagets element based on ID attribute of HTML DOM.
getElementsByTagName():
This function targets element based on tagname. It returns an array of elements.
Dynamically updating the elements:
We can change the style attributes of any element by javascript. In this case, we use css properties name. like for margin-left => marginLeft. see more at Mozilla Developer Network.
Create element:
var p = document.createElement("p"); // first the element is created
p.style.color = "red";
p.className = "myClass";
p.innerHTML = "I am a new para added to body"; // added style to the element
var body = document.querySelector("body"); // took the parent of insertion
body.appendChild(p); // attached the element
Remove Element:
<ul>
<li>c++</li>
<li id="courses">java</li>
<li>js</li>
<li>php</li>
</ul>
//--- script----
var courses = document.getElementById("courses");
courses.parentNode.removeChild(courses);
In the above example, first we get the element to be deleted. then we go to its parent node by “.parentNode”. From parent node we use “.removeChild()” function to delete the desired child element.
Leave a Reply