Skip to content

Instantly share code, notes, and snippets.

View StevenWuTG's full-sized avatar

Steven Wu StevenWuTG

  • New York
View GitHub Profile
<body>
<div class="grandparent" id="grandparent">
<!-- "parent-1" & "parent-2" belongs to "grandparent"-->
<div class="parent" id="parent-1">
<!-- "child-1" & "child-2" belongs to "parent-1"-->
<div class="child" id="child-1">
</div>
<div class="child" id="child-2">
</div>
</div>
const grandparent = document.getElementById("grandparent")
//or
const parent2 = grandparent.getElementById("parent-2")
//selecting multiple classes
const parents = document.getElementsByClassName("parent")
//or if you want to target specific classes from specific parent nodes
const parent2 = document.getElementById("parent-2")
const childrenOfParent2 = parent2.getElementsByClassName("child")
//which will return an array of the divs of child-3 & child-4
//find a element node by a class using the "." css selector before the class
const grandparent = document.querySelector(".grandparent")
//or
//find a element node by a id using the "#" css selector before the id
const parent2 = grandparent.querySelector("#parent-2")
//find element nodes by a class using the "." css selector before the class
const parents = document.querySelectorAll(".parent")
//will return the array of parent-1 & parent-2
//or
const childrenOfParentIndex0 = parents[0].querySelectorAll(".child")
//will return the array of child-1 & child-2
//first you need to find a single element node
const parent1 = document.querySelector("#parent-1")
const grandparent = parent1.parentElement
//this will return the entire grandparent node containing the parents and the children
//first you need to find a single element node
const parent2 = document.querySelector("#parent-2")
const parent1 = parent2.previousElementSibling
//this will return the node with the id of parent-1
//first you need to find a single element node
const parent1 = document.querySelector("#parent-1")
const parent2 = parent1.nextElementSibling
//this will return the node with the id of parent-2
//first you need to find a element node
const parent2 = document.querySelector("#parent-2")
const firstChildOfParent2 = parent2.firstElementChild
//will return the node with the id of child-3 which is the first child of parent-2
//first you need to find a element node
const parent2 = document.querySelector("#parent-2")
const lastChildOfParent2 = parent2.lastElementChild
//will return the node with the id of child-4 which is the last child of parent-2