You can use the parentElement
property to traverse the document tree of elements until the root in order to evaluate the depth of each element and through that decide on the element closest to the root:
// get all matching nodes as NodeList
const resultNodes = document.querySelectorAll(".someclass")
// convert NodeList object to Array of nodes
const results = [...resultNodes.keys()].map(key => resultNodes[key]);
// Compute the depth in the DOM tree for each element
const resultsWithDepth = results.map(result => {
return {
element: result,
depth: computeDOMElementDepth(result, 0)
}
})
getElementWithLowestDepth(resultsWithDepth);
// Computes the depth of a DOM element in an end-recursive fashion
function computeDOMElementDepth (element, currentDepth) {
if (element.parentElement === null) {
return currentDepth;
}
return computeDOMElementDepth(element.parentElement, ++currentDepth);
}
// Filters out the element highest in the DOM. (First element takes precedence)
function getElementWithLowestDepth (elements) {
return elements.reduce((element1, element2) => {
if (element2.depth < element1.depth) {
return element2;
}
return element1;
})
}