Reading and Writing Element Attributes
Remember:
<element attribute="value">InnerHTML</element>
Example:
<a id="next-page" class="button red-border" href="/pages/2">Next<a>
const nextPage = document.querySelector("#next-page");
// Read attributes
nextPage.getAttribute("class"); // "button red-border"
nextPage.getAttribute("href"); // "/pages/2"
// Write attributes
nextPage.setAttribute("href", "/pages/3");
// Check for attribute existence
nextPage.hasAttribute("style"); // false
// Remove attribute
nextPage.removeAttribute("id");
Navigating Through HTML Elements
Example:
<div class="container">
<h1>Countries</h1>
<ol id="list-of-countries">
<li>Brazil</li>
<li>Japan</li>
<li>United States of America</li>
</ol>
</div>
const list = document.querySelector("ol");
const header = document.querySelector("h1");
// Get parent element
list.parentElement; // <div class="container">...</div>
// Get child elements
list.children; // [li, li, li]
list.firstElementChild; // <li>Brazil</li>
list.lastElementChild; // <li>Unites States of America</li>
list.children[1]; // <li>Japan</li>
// Get sibling elements
list.previousElementSibling; // <h1>Countries</h1>
header.nextElementSibling; // <ol id="list-of-countries">...</ol>
// Since these all return other HTMLElement objects you can use chaining
list.children[1].parentElement.parentElement; // <div class="container">...</div>
Creating and Inserting Elements
Example:
<div class="container">
<h1>Countries</h1>
<ol id="list-of-countries">
<li>Brazil</li>
<li>Japan</li>
<li>United States of America</li>
</ol>
</div>
const list = document.querySelector("ol");
// Create a new list element and set it's inner HTML to the word "Canada"
const newListElement = document.createElement("li");
newListElement.innerHTML = "Canada";
// Inster the new list element before the end of the parent ordered list element
list.insertAdjacentElement("beforeend", newListElement);