Document Object Model(DOM) Interaction

Check the updated DevOps Course.

Prashant Lakhera
Devops World
3 min readMar 11, 2017

--

Course Registration link:

Course Link:

YouTube link:

How to grab HTML elements from the DOM

HTML elements are properties of the DOM

Now let see some important document attributes

document.URL: Returns actual URL of the website

document.body: Returns everything inside body

document.head: Returns everything in the head of page

document.links: Return all the links on the page

Let see some methods for grabbing elements from the DOM

document.getElementById()

Returns elements based on whatever Id we passed

document.getElementByClassName()

Returns elements based on whatever classname we passed, and then it return lists of all the items belonging to that class name

document.getElementByTagName()

Return lists of all the items belonging to that tag name

document.querySelector()

Returns the first element matches the css style selector

document.querySelectorAll()

Returns all the elements matches the css style selector

Now taking this code as example let try to grab html elements

document.URL

As you see it document.url return the actual url of the website

Now let see document.body

document.body
document.head

Returns everything on the head page

document.links

In case if there are links in our page

These are all attributes not methods so we don’t need to put parentheses in front of it

Now looks at important/useful methods

document.getElementById
document.getElementsByClassName

NOTE: It’s spelled as Elements(extra s)

document.getElememtsByTagName
document.querySelector/querySelectorAll

# for id

. for class

As mentioned earlier query selector allow us to grab things based on css selectors and save lot of our time. So querySelectorAll returns all the objects whereas querySelector returns all object.

Now let see how its helpful for us

Take a simple example where I want to change the Header color

Change Header Color

--

--

Prashant Lakhera
Devops World

AWS Community Builder, Ex-Redhat, Author, Blogger, YouTuber, RHCA, RHCDS, RHCE, Docker Certified,4XAWS, CCNA, MCP, Certified Jenkins, Terraform Certified, 1XGCP