Document object Model in Javascript

Document Object Model

When a page is loaded, the browser creates the DOM for the web page. The DOM represents the document as a node tree, where each node represents each element of html.

image.png

Document Object Model is an API that represents and interacts with HTML documents, with the help of DOM, accessing elements in an HTML page and/or editing them or even adding new elements to the page will become quite easy for us.

Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them, you can change the document's structure, style, or content. Event listeners can be added to nodes and triggered on an occurrence of a given event.

Fetching elements

You can use the 'document' object to access the elements on your HTML page.

You can access elements from the following selectors -

  1. document.getElementById("idname") -> 1st matching result , if the element is not found then null
  2. document.getElementsByTagName("tagname") -> html collection of all element by tag
  3. document.getElementsByClassName("classname") -> html collection of all elements by class
  4. document.querySelectorAll("css-selector") -> nodelist , if no match then null, if invalid selector then error.
  5. document.querySelector("css-selector") -> 1st matching result, if no match then null, if invalid selector then error.

Modifying DOM

We can modify the content of DOM using

  1. innerHTML -> To modify the space,tag.
  2. innerText -> To just modify text inside tag, no spacing
  3. innerContent -> Can modify text with spacing also.

Styling

-> we can also change css properties of the DOM element

let element = document.getElementById("idName");
element.style.fontSize="20px";

-> Above example we are changing the font-size.We need to write name of css property in camel case.

cssText

-> Using cssText we can add more than 1 css properties.


const myStyles = `
    display: block;
    width: 80%;
    background-color: red;
    border: 2px;
    font-size: 5em;
    color: white;
    margin: 20px;
    padding-left: 10px;
    padding-bottom: 10px;
    border: 2px solid black;
`;
const element = document.querySelector('.demo');

element.style.cssText = myStyles;

Traversing DOM

-> To get parent element

document.getElementsById("idName").parentElement

-> To get children elements

document.getElementsById("idName").firstElementChild
document.getElementsById("idName").lastElementChild

-> To get siblings elements

document.getElementsById("idName").previousElementSibling
document.getElementsById("idName").nextElementSibling