DOM

The DOM(Document Object Model) represents the web page as a tree-like structure that allows JavaScript to dynamically access and manipulate the content and structure of a web page.

 

Selectors in JavaScript

Selectors get specific elements from the DOM, based on IDs, class names, tag names.

 

getElementById()

getElementsByClassName()

getElementsByTagName()

querySelector()

querySelectorAll()

 

<div id="foo">Whizz Bang </>


const el = document.getElementById("foo")

console.log(el.innerHTML)

// Whizz Bang

 


 

querySelector <- just gets the first match

 

<html>>
‹head>
<title></title>
</head>
< body>
‹div class="myClass" ›Element 1‹/div> 
‹div class="myClass">Element 2</div> 
‹div class="myClass"› Element 3</div>
<script src="/teach/index.js"*/script>
</ body>
</html>


var el = document.querySelector(".myClass")

// Element1

 

querySelectorAll() <- gets an array of matches

<html>>
‹head>
<title></title>
</head>
< body>
‹div class="myClass" ›Element 1‹/div> 
‹div class="myClass">Element 2</div> 
‹div class="myClass"› Element 3</div>
<script src="/teach/index.js"*/script>
</ body>
</html>



var els = document.querySelectorAll(".myClass")

els.forEach( el => console.log(el) )

 

What are the methods to modify elements properties and attributes.

<div id="myElement">Hello world</div>



document.getElementById("myElement").textContent = "nice"


document.getElementById("myElement").innerHTML = "<b>Welcome</b>"




document.getElementById("myElement").setAttribute("data-info", "new value")

var info = document.getElementById("myElement").getAttribute("data-info")

document.getElementById("myElement").removeAttribute("data-info")




document.getElementById("myElement").style.setProperty("color", "blue")


document.getElementById("myElement").classList.add("highlight")
document.getElementById("myElement").classList.remove("highlight")
document.getElementById("myElement").classList.toggle("highlight")




 

How to create new elements in the DOM using JavaScript

// createElement

var newDiv = document.createElement('div')

newDiv.textContent = 'New created div')


document.body.appendChild(newDiv)


// CloneNode()

<div id="parenetElement">
    <h1>Existing Element</h1>
</div>



var el = document.getElementById('parentElement')
var clonedEl = el.cloneNode(true)

clonedEl.textContent = "Wow a clones element"

document.body.appendChild(clonedEl)

 

// createTextNode()

var parentElement = document-getElementById("parentElement");

// Create a new text node
var newText = document.createTextNode(" This is some text.");

// Append the text node to the parent
parentElement.appendChild (newText);




// Output

‹div id="parentElement">
   ‹h1>Existing Element</h1>
   " This is some text."    <- just a dump of text
</div›