There is no one function/property in the DOM API that equates to jQuery's parents
, but you can easily build one with few lines of code using a loop with:
parentElement
, which provides a reference to the element's parent element or null
. (Or you could use parentNode
, but you have to check for both null
and document
to know when to stop.)
matches
if you want only parent elements matching a selector
(jQuery takes a set-based approach to DOM manipulation and traversal, whereas the DOM API takes a per-element/node approach. I won't address doing the set thing here.)
Example:
function getParents(element, selector) {
const parents = [];
let parent = element;
while (parent) {
// Include this "parent" if either we don't have a selector at all,
// or we have one and it matches
if (!selector || parent.matches(selector)) {
parents.push(parent);
}
parent = parent.parentElement;
}
return parents;
}
Runnable version:
const elm = document.getElementById("target");
console.log("All divs:");
showElements(getParents(elm));
console.log("Only divs with a data-test attribute:");
showElements(getParents(elm, "[data-test]"));
function getParents(element, selector) {
const parents = [];
let parent = element;
while (parent) {
// Include this "parent" if either we don't have a selector at all,
// or we have one and it matches
if (!selector || parent.matches(selector)) {
parents.push(parent);
}
parent = parent.parentElement;
}
return parents;
}
function showElements(elements) {
console.log(Array.from(elements,(e) => e.nodeName + (e.id ? "#" + e.id : "")));
}
.as-console-wrapper {
max-height: 100% !important;
}
<div id="outermost" data-test>
<div id="middle">
<div id="inner" data-test>
<div id="target"></div>
</div>
</div>
</div>
The site https://youmightnotneedjquery.com/#parents has lots of information for doing jQuery-like things only with native DOM functions (for instance: parents
, which has a function very very similar to the above, but using parentNode
rather than parentElement
and therefore including the check for document
).
parents()
method?" – Grosswhile ((element = element.parentElement)) { if (element.matches('.className')) { result.push(element) } }
– Assorted