A Document object represents the HTML document that is displayed in the window. It is basically the structured representation of the HTML document.
It can be a further Tree of nodes/elements (any of the HTML tags, body tags, pretty much anything that is in the document) created by the browser.
JavaScript can be used to read/write/manipulate the DOM
.
The DOM
is object-oriented which means that each node has a set of properties as well as methods that we can change and we can remove too.
Actually, our browser gives the window object and inside that, we have the document object and underneath that we are having the Root
element which is having the HTML
tag or element and from there we are having the head
tag and body
tag.
In the above diagram, we could easily see that body
tags and head
tags are actually siblings due to the same level in that particular tree.
And in the head
, we have the meta
tags and we have the title
tags. on the other hand in the body
tags, we are having h1
tags, links
, semantic tags like "My link"
, "My header"
Methods to Select an Individual Element Node-
Following are the methods to select an individual element in the tree:-
- getElementById(‘id’): Uses the unique value of the element’s id attribute. The HTML must have an id attribute for the method to select it. For example – getElementById(‘one’)
- querySelector(‘CSS selector’): Uses a CSS selector, returns the first matching element.
For example – querySelector(‘h1’)
The code below combines these methods to add styling to the webpage.
<script type="text/JavaScript">
document.getElementById('one').style.color="maroon"; //change font color
document.querySelector("h1").style.backgroundColor = "blue"; //change background color
</script>
Methods to Select Multiple Elements (NodeLists)
There are three common ways to select multiple elements in the tree:
- getElementsByClassName(): Selects all the elements that have a specified value for the class attribute. For example – getElementsByClassName(‘mandatory’)
- getElementsByTagName(): Selects all the elements that have the specified tag names. For example – getElementsByTagName(‘h1’)
- querySelectorAll(): Uses a CSS selector, returns all the matching elements. For example – querySelectorAll(‘li.mandatory’)
The above methods always return a NodeList, even if the list contains only a single element. This is so important to remember because you need to use square brackets [ ] if you want to access any element in the NodeList.
The following code explains all the methods of returning a NodeList.
<script type="text/JavaScript">
var list_qs = document.querySelectorAll("li.mandatory"); //NodeList
list_qs[0].style.backgroundColor = "blue"; //change background color
var list_cn = document.getElementsByClassName('mandatory'); //NodeList
list_cn[0].style.color="white"; //change font color
var list_tn = document.getElementsByTagName('h1'); //NodeList
list_tn[0].style.color="gray"; //change font color
</script>