We could use the selectors target at nodes in the tree of DOM, just like the selectors in CSS;
example:
div.display
.display
#container > .display
div#container > div.display
DOM methods
When your HTML code is parse by a web browser, it is cconverted to the DOM. Now these nodes are JavaScript objects that have many properties and methods attached to them. These properties and methods are the primary tools we are going to use to manipulate our webpage with JavaScript.
Query selectors
element.querySelector(selector) - returns a reference to the first mactch of selector.
element.querySelectorAll(selectors) - returns a “NodeList” containing references to all of the matches of the selectors.
Element creation
document.createElement(tagName, [options]) - creates a new element of tag type tagName. [options] in this case means you can add some optional parameters to the function. Don’t worry about these at this point.
1
const div = document.creatElement("div");
Append elements
parentNode.qppendChild(childNode) - appends childNode as the last child of parentNode.
parentNode.insertBefore(newNode, referenceNode) - insert nowNode into parentNode before referenceNode.
Remove elements
parentNode.removeChild(child) - remove child from parentNode on the DOM and returns a reference to child.
Altering elements
To altering the properties of an element, we need to get a reference of it first.
1 2
// creates a new div refereced in the variable 'div' const div = document.creatElement("div");
Adding inline style
1 2 3 4 5 6 7 8
// adds the indicated style rule to the element in the div variable div.style.color = "blue";
This might seem like a lot of you’re attaching lots of similar events listeners to many elements. There are a few ways to go about doing that more efficiently. We learned above that we can get a CodeList of all of the items matching a specific selector with querySelectorAll('selector'). In order to add a listener to each of then, we need to iterate through the whole list, like so:
// buttons is a node list. It looks and acts much like an array. const buttons = document.querySelectorAll("button");
// we use the .forEach method to iterate through each button buttons.forEach((button) => { // and for each one we add a 'click' listener button.addEventListener("click", () => { alert(button.id); }); });