Skip to content

Instantly share code, notes, and snippets.

@Martin-Alexander
Last active May 5, 2020 17:23
Show Gist options
  • Save Martin-Alexander/1c578574ef787a131e59a9b679a044b0 to your computer and use it in GitHub Desktop.
Save Martin-Alexander/1c578574ef787a131e59a9b679a044b0 to your computer and use it in GitHub Desktop.

DOM Manipulation/Parsing

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment