Table of Contents
When you open a website in your browser, the browser builds something call Document Object Module (referred to as DOM ).
DOM is a tree-like structure of an HTML page. All the tags in an HTML page are represented as nodes in the DOM tree. The browser uses this DOM to draw a page on the screen.
DOM Tree Structure
Nodes in the document are referred to as elements although not all nodes are elements. Each DOM node has a nodeType which contains a code that identifies the type of the node.
For example : if you run document.nodeType in your browser console (ctrl+shift+j in chrome) on HTML page you get 9 as output. Which is the nodeType value of document.
more node type values can be found here
Siblings: Using nextElementSibiling and previousElementSibiling we can access the previous and next siblings of the node respectively.
Code - siblings
Children: Using properties lastElementChild, firstElementChild and children we can get the required child of the current node
Code - children
There are many other properties such as nodeValue, baseURI, etc which you can refer to here
(Note: Using nextSibling or lastChild will give text output because the whitespace between the lines of code is treated as a text element. So it's better to use nextElementSibiling or lastElementChild )
Accessing Elements: The element in the DOM can be accessed using the following methods
getElementById(): returns an element with the given Id. Each element has a unique id so it only returns one element always.
getElementsByTagName(): returns the total number of elements present with the given tag.
3.getElementsByClassName(): returns the total number of elements present with the given class name.
4.querySelector(): returns only the first element present with the given query name.
5.querySelectorAll(): returns the total number of elements present with the given query name.
In querySelector parameters should be passed as follows
tag - 'tag' class - '.name' id - '#id"
Code - elements
Adding Elements: In order to add elements to the DOM you first need to create an element using createElement() method. After creating an element we append using the appendChild() to the parent element to which we want to add the created element.
(PS: This is my first article any feedback is very helpful to me, so please take a few seconds to give feedback. If there are any mistakes please post in the comments. Thank You.)