DOM tree structure

Using JavaScript to Manipulate the DOM

Accessing DOM Elements

The query selector finds the first element or node that matches a specified parameter. The most common ways a query selector is used are to access elements of a certain type, elements with a certain id, and elements with a certain class. More complex query selectors can be written that account for more parameters and can exclude elements that match specified parameters.

document.querySelector("element");
//Gets element that matches specified typedocument.querySelector(".class");
//Gets element that matches specified classdocument.querySelector("#id");
//Gets element that matches specified id
document.querySelectorAll("element");
//Gets element that matches specified type
document.getElementById("elementId");
document.getElementsByClassName("class12");
//Gets all elements with class1document.getElementsByClassName("class1 class2");
//Gets all elements with class1 and class2

HTML Attributes

Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript…

www.w3schools.com

element.getAttribute("attributeName");
//Gets information about specified attributeelement.attributes
//Gets information about all attributes of an element

Adding, Changing, and Removing DOM Elements

To add a new node to the DOM, the element must first be created then it must be added to the document or to another node as a child.

const newH1 = document.createElement('h1')
//Creates new h1 
newH1.textContent = 'This is a new h1'
//Sets text of h1 
document.body.appendChild(newH1)
//Adds new h1 to the DOM
document.getElementById("ourDiv").innerHTML = 
"<button>Click me!</button>";
const btn = document.querySelector("button")btn.innerText = "Clicked!";btn.textContent = "Clicked!";
document.querySelector("p").remove()
//Removes first p tag from pagenode.removeChild(child);
//Removes child node from parent node

Manipulating Element Attributes

To add an attribute to an element the node’s attribute can be assigned a value. This same format can be used to modify existing attributes.

node.attribute = attributeValue
element.setAttribute("attributeName", attributeValue)
element.removeAttribute("attributeName")

Manipulating Element Styling

An element’s style can be modified by making a CSS styling declaration and using the style property.

element.style.stylingProperty = stylingValue
element.style.backgroundColor = "blue"
element.style.font-size = 12pt

Triggering DOM Changes

Changes to the DOM are triggered by events. These events are actions that a user takes when interacting with a webpage. There are actions that can be triggered by acting on a particular element and actions that can be triggered by interacting with the entire window. In order to use an event to trigger an action, an event listener must be attached to the window or to a node.

targetNode.addEventListener("eventType", fuctionToTrigger);