D Dev Notebook

JavaScript DOM Manipulation

DOM - Document Object Model

Document Object Model is a tree-like representation of the contents of a webpage - a tree of “nodes” with different relationships depending on how they’re arranged in the HTML document.

dev notebook
<div id="container">
    <div class="box1"></div>
    <div class="box2"></div>
</div>
  • #container is parent of .box1 and .box2
  • .box1 and .box2 is child of #container
  • .box1 and .box2 are sibling

DOM Methods

DOM Methods - DOM methods are actions that can perform on HTML elements

Finding the HTML Elements

  • find element with id
document.getElementById(“hello”)	
  • find element with class
document.getElementsByClassName(“hello”) 
  • find element with tag name
document.getElementsByTagName(“name”)
  • find element with id, class or tag name
document.querySelector(selector) 
  • find all element with id, class or tag name
document.querySelectorAll(selectors)	

Changing HTML elements

  • change html
document.querySelector(selector).innerHTML =<h1>hello</h1>
  • change element text
document.querySelector(selector).innerText =  “Hello, World!!!
  • add attribute
document.querySelector(selector).setAttribute(‘class’, ‘hello’)  

Adding and Removing elements

coming soon

Creating new div

let div = document.createElement('div');
div.id = 'content';
div.innerHTML = '<p>CreateElement example</p>';
document.body.appendChild(div);

Changing the CSS style

const h1 = document.querySelector("h1");
h1.style.color = "blue";

On this page