JS DOM: Get Parent, Child, Sibling

By Xah Lee. Date: . Last updated: .

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 null if none.

element.previousElementSibling

Value is the previous sibling element, or null if none.

element.nextElementSibling

Value is the next sibling element, or null if 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 null if 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 null if 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.previousSibling
node.nextSibling
node.firstChild
node.lastChild
node.childNodes
node.hasChildNodes()

Return true if it has children, including Whitespace Nodes. Else false.

document.getElementById("xd1d13").hasChildNodes();