The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a web page as a tree of objects that can be manipulated with JavaScript.
Web browser construct a DOM when it loads an HTML file, and that is why we will use getElementById() in js!
getElementByTag: returns a HTML collection chosen by tags(e.g. <h1>, <h4>)
querySelector: select an element with specific query. The most powerful and flexible.
1 2 3 4 5 6 7 8
// Select the first <p> element const firstParagraph = document.querySelector('p');
// Select the first element with class "example" const exampleElement = document.querySelector('.example');
// Select the element with id "header" const header = document.querySelector('#header');
querySelectAll: returns a NODELIST, which is static. (select all the elements)
Nodelist has built-in forEach methods!
DOM navigation
For the DOM structure, it can be abstracted into a tree structure. Thanks to DOM navigation, we can easily navigate through different ids and selectors.
Through flexible query selector and DOM navigation, we can freely choose the element we want in complex HTML components, rather than simply using the getElementByID() methods.
Add & Change & Hide & Show HTML
We can modify some properties of html elements in js files, but beyond that!
// Add HTML elements const h1_new = document.createElement("h1"); const new_id = "just a test" h1_new.textContent = "I like pizza"; h1_new.id = new_id; // you can add more styles and properties here!
// insert into the DOM structure // ! using append and prepend document.body.append(h1_new); document.body.prepend(h1_new); document.getElementById("dessert").append(h1_new);
// or using the insertbefore method document.body.insertBefore(h1_new, document.getElementById("dessert"));
// remove HTML elements // append as its child const all_childs = document.getElementById("dessert").children; console.log(all_childs); document.getElementById("dessert").removeChild(document.getElementById(new_id)); console.log(all_childs);
// * a small demo: adding ordered list const new_fruit = document.createElement("li"); new_fruit.textContent = "coconut"; new_fruit.id = "coconut"; // assume we need to insert this after the apple in the list document.getElementById("orderlist-demo").insertBefore(new_fruit, document.getElementById("apple")); // or we can use the method below for more flexible control constListItems = document.querySelectorAll("#orderlist-demo li") // console.log(ListItems); document.getElementById("orderlist-demo").insertBefore(new_fruit, ListItems[2]);
Hide & Show
You can use the onclick method or using event listener.
The classList property is a powerful DOM feature that provides methods to work with an element’s CSS classes in JavaScript. It’s a cleaner alternative to manually manipulating the className property.
// ! toggle: remove if present, add if not. // replace(oldClass, newClass) // contain(): return true or false
CallBack Hell
For JavaScript is single-threaded and relies on the event loop mechanism to handle asynchronous operations, it will cause error when calling functions with time stuck without using callback.
For example, I want to operate 4 tasks in sequential time order, I can use callback as follows:
We can use json.parse() to parse a string back to a js object (or an array).
fetch method in json
We can use fetch method to fetch json files in js.
1 2 3 4 5 6 7 8 9 10 11 12 13
fetch("demo1.json") .then(response => { if (!response.ok) thrownewError("Network error"); return response.json(); }) .then(values => { if (Array.isArray(values)) { values.forEach(value =>console.log(value)); } else { console.log("Received data is not an array:", values); } }) .catch(error =>console.error("Fetch failed:", error));
Or we can pass APIs!
1 2 3 4 5 6 7 8 9 10 11 12 13
fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => { if (!response.ok) { thrownewError('Network response was not ok'); } return response.json(); // Parse JSON data }) .then(data => { console.log(data); // Process the data }) .catch(error => { console.error('Error:', error); });