JS DOM: Get Parent, Child, Sibling
Methods for getting element nodes only
element nodes are those represented by a normal markup tag. JS DOM: Node, Node Type
node.parentElement-
Value is the parent element of node, or
nullif none.
element.previousElementSibling-
Value is the previous sibling element, or
nullif none. element.nextElementSibling-
Value is the next sibling element, or
nullif none.const xx = document.getElementsByTagName("p"); if (xx.length === 0) throw (new Error(`p tag not found`)); const xnext = xx[0].nextElementSibling; if (!xnext) throw (new Error(`no next element sibling`)); xnext.style.color = "red";
element.firstElementChild-
Value is the first child element, or
nullif none.// create a div const xdiv = document.createElement("div"); // create inner html xdiv.innerHTML = ` <ul id="Sj6ht"> <li>A</li> <li>B</li> </ul> `; // add to the page document.body.prepend(xdiv); // get the list const xlist = document.getElementById("Sj6ht"); console.log( xlist.firstElementChild.firstChild.nodeValue === "A", ); // true element.lastElementChild-
Value is the last child element, or
nullif none.
element.children-
Value is the element's child elements.
result is a Live Object and HTMLCollection.
const xx = document.body; for (let x of xx.children) x.style.color = "green";
Methods for getting any node type
The following gets any Node Type, including text node or Whitespace Nodes .
node.parentNode-
// the html element const xx = document.documentElement; // parent node is document console.log(xx.parentNode === document); // parent element is null console.log(xx.parentElement === null); node.previousSiblingnode.nextSiblingnode.firstChildnode.lastChildnode.childNodes-
node.hasChildNodes() -
Return
trueif it has children, including Whitespace Nodes. Elsefalse.document.getElementById("xd1d13").hasChildNodes();