The Document Object Model is a programming interface for HTML (and XML) documents, and represents the tree structure and content of a document on the web. The main language of DOM manipulation is JavaScript.
Selections
The parent object of a browser is a window object. This object contains most, if not all, of the functionality that can be run from a JS script. For example, the window object contains a method called alert. Thus, we can use window.alert() and run it to the same effect. However, because this is such a foundational part of the process, the functions needn’t be called with reference to window itself.
Another important attribute of the window object is the document. This is the DOM itself. As a result, we will often use document.<something> notation to select specific elements from the document.
Single element selector
A classic selector is getElementById. If this element is logged what we will see in the console is the element itself:
// Single element selector
const form = document.getElementById('my-form');
console.log(form)Assuming appropriate HTML, this is what will be printed:
<form id="my-form">
<h1>Add User</h1>
<div class="msg"></div>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
</div>
<div>
<label for="email">Email:</label>
<input type="text" id="email">
</div>
<input class="btn" type="submit" value="Submit">
</form>Another common selector for single elements is the querySelector (which has basically the same functionality as jQuery):
// Note the use of "." notation, like in CSS, to select HTML classes
console.log(document.querySelector(".container"))Note
querySelectoris a single element selector so it will only return the first match. See Multiple element selector.
Multiple element selector
To select multiple elements we can use the modern querySelectorAll. This will return a NodeList, which is very similar to Arrays - so much so that array methods can run on NodeList objects.
Other methods that select multiple elements include:
getElementsByClassName(here we don’t use ”.” notation like in CSS!)- This will return an
HTMLCollection, which is an array-like but not array-compatible object
- This will return an
getElementsByTagName
If we want to loop over each item, we might do the following:
const items = document.querySelectorAll(".item");
items.forEach((item) => console.log(item));DOM manipulation
After selecting elements, we can use JS to manipulate the DOM (and therefore the user interface). For example, we can remove, change, and otherwise manipulate the list items under a ul that has a class of items:
// DOM Manipulation
const ul = document.querySelector(".items")
// ul.remove();
// ul.lastElementChild.remove();
ul.firstElementChild.textContent = "hello";
ul.children[1].innerText = "Meow";
ul.lastElementChild.innerHTML = "<h1>MEOW!</h1>"We can also change the style of an element:
const btn = document.querySelector(".btn");
btn.style.background = "red"Events
We can create events in response to things happening in the document. For example, it is possible to change a color or the UI of something if a button is clicked:
// Events
// Both functions do the same
btn.addEventListener("click", (eventVar) => {
eventVar.preventDefault();
console.log("click!")
})
btn.addEventListener("click", function(e) {
e.preventDefault();
console.log("clickity");
})We can also print the event itself to the console, which includes a significant amount of information - including mouse position, key-presses, etc. This itself is an object that can be accessed with dot notation:
// event print log
click { target: input.btn
, buttons: 0, clientX: 226, clientY: 364, layerX: 226, layerY: 281 }
altKey: true
altitudeAngle: 1.5707963267948966
azimuthAngle: 0
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 226
clientY: 364
composed: true
ctrlKey: false
etc, etc, etc ...Each of these attributes can be asses with e.altKey, for example. A useful one is to use:
console.log(e.target.className) // prints btnInfo
We can use event listeners to change specific attributes, including the class of an element. Thus, assuming we have a coherent CSS style sheet (in this case with a “bg-dark” class) we can change the color scheme:
btn.addEventListener("click", (eventVar) => {
eventVar.preventDefault();
document.querySelector("#my-form").style.background = "#ccc"
document.querySelector("body").classList.add('bg-dark');
})