Know your DOM?
When something related to web development clicks in our mind, we think of HTML and JavaScript. But these two terms totally different from each other. How they even interacting with each other? Now let's read to get the answer of this…
Both JavaScript and HTML are two different things. HTML is a markup language and JavaScript is code. it all happens through a representation of your page, called DOCUMENT OBJECT MODEL , or the DOM.
WHERE DOES THE DOM COMES FROM?
when you load your page into the browser, not only the does the browser read the HTML and then render it to display. it also creates a set of objects that represent your markup. These objects are stored in DOM.
HOW DOES JS INTERACT WITH DOM?
JS interacts with the DOM to get elements using methods like ‘getElementById’ which is inbuilt is JS library. Then, after grabbing an element, following things you can do with an element object through JS.
- Get the context(text or HTML)
- Change the content
- Read an attribute.
- Add an attribute.
- Change an attribute
- Remove an attribute
EX:
- var userName = document.getElementById(“#user-name”)
- userName = Variable used to store the value, which gets through element ID.
- document = It represents the entire page in your browser and contains the complete DOM
- getElementById = Here we are asking the document to get us an element by finding the element that matches the id.
- "user-name" = Its element ID.