DOM Manipulation ShortHand in JS

DOM (Document Object Model)

  1. it is the structural representation of HTML file .it is like a tree of nodes or element which is similar to that of objects having properties which we can use to change the style of the page.

  2. document.all[index] all is the array of all the elements present in the tree or any html page.we can access it using the index no.

  3. textContent and innerText both used to display text on browser but the difference is textContent is not style attentive but innerText is. innerHTML is used to write HTML code in script file.we can also change style using .style.propertyName on the selected element.

  4. there are no of selector present to select DOM elements. getElementById, getElementByClassName,getElementByTagName,querySelector it grab the first match only for eg if we want to select the last item in a list using querySelector() then we can write as document.querySelector('.list-item:last-child') similary nth-child(no) to select any child in the list item class. querySelectorAll() will select all the element which matches the criteria. like if we want to select all even or all odd item in a list using querySelectorAll then we can use the syntax: document.querySelectorAll('.list-item:nth-child(odd/even)')

  5. parentNode/parentElement property gives the parentNode of the given selected criteria.

  6. childNode/children (preferable as it does not consider line break) property to access childs of the given selected element criteria.

  7. firstChild/firstElementChild(preferable for same reason) used to get first child among all similary lastChild/lastElementChild is for fetching last child.

  8. nextSibling/nextElementSibling(preferable) method is used to fetch the next sibling in the line of child. similary, previousSibling/previousElementSibling is used to fetch the previous element comes in the line of child.

  9. createElement() method is used to create element in the script file. ex:

 var newDiv = document.createElement('div')

//add class

 newDiv.class = 'div-class'

//add id

 newDiv.id = 'div-id'

// adding attribute

newDiv.setAttribute('title', 'title-value')

//create text node

var newDivText = document.createTextNode('Hello World')

//add text to div

newDiv.appendChild(newDivText)

//Where to insert on DOM

var container = document.querySelector('header .container')
var h1 = document.querySelector('header h1')
container.insertBefore(newDiv, h1)