DOM manipulation
Document Object Model - way to represent webpage in hierarchical order
- tree like structure to manipulate html object in javascript
- allow content updated and user interaction (not static)
DOM data types
- Document - root of the entire DOM
- Element - Node in the DOM tree
- NodeList - Array of elements
Methods of the document object
- write("string") - write to the document
- getElementById(), getElementByName(), getElementByTagName(), getElementByClassName()
<body>
<label>Enter Value 1: </label>
<input type="text" id="val1" />
<br />
<br />
<label>Enter Value 2: </label>
<input type=".text" id="val2" />
<br />
<button onclick="getAdd()">Click To Add</button>
<p id="result"></p>
<script type="text/javascript">
function getAdd() {
// Fetch the value of input with id val1
const num1 = Number(document.getElementById("val1").value);
// Fetch the value of input with id val2
const num2 = Number(document.getElementById("val2").value);
const add = num1 + num2;
console.log(add);
// Displays the result in paragraph using dom
document.getElementById("result").innerHTML = "Addition : " + add;
// Changes the color of paragraph tag with red
document.getElementById("result").style.color = "red";
}
</script>
</body>
Writing to DOM
// Create a new div element
let element = document.createElement("div");
// Create a new text node
let textNode = document.createTextNode("Some text"); // Adding and removing elements
element.appendChild(textNode); element.removeChild(textNode);
// Making changes to attributes
button.setAttribute("disabled" , "");
Change and getting styles
// Changing element.style
element.style.left = "50px";
// Note: don't forget units!
// Adding 5px to the left value
let newLeft = parseInt(element.style.left, 10) + 5 + "px"; element.style.left = newLeft;
element.style.backgroundColor = "red";
// Note: camelCase
// Getting computed style
let computedStyle = window.getComputedStyle(element, null) let bgColor = computedStyle.getPropertyValue("backgroundcolor")
Change Classes
// Changing element.classList
element.classList.add("class"); element.classList.remove("class"); element.classList.toggle("class"); element.classList.contains("class");
// returns true if class exists on element