Apologies for this kind of question, but I can't find an answer on You Might Not Need jQuery or anywhere else online and I'd really like to know:
What is the pure JavaScript equivalent of jQuery's .parents() method?
For example, it would be great to know how to do this in pure JavaScript:
jQuery(element).parents('.className');
There is no one function/property in the DOM API that equates to jQuery's parents()
. There is the parentNode
property (and as Oriol points out, the parentElement
property, which will prevent your going from document.documentElement
up to document
), which is the parent node (or parent element) of the element on which you access it, or null
if it doesn't have one. To roughly match jQuery's parents()
, you can loop on it (e.g., get the parentNode
/parentElement
of the parentNode
/parentElement
, etc.) to find all the parents. As squint notes, on vaguely-modern browsers at each level you can use matches
to check if the parent matches a selector (to match jQuery's behavior with parents()
when you pass it a selector).
jQuery takes a set-based approach to DOM manipulation and traversal, whereas the DOM API takes a per-element/node approach.
Example:
var elm = document.getElementById("target");
var parents = getParents(elm);
console.log(Array.prototype.map.call(
parents,
function(e) {
return e.nodeName + (e.id ? "#" + e.id : "");
}
).join(", "));
function getParents(e) {
var result = [];
for (var p = e && e.parentElement; p; p = p.parentElement) {
result.push(p);
}
return result;
}
<div id="outermost">
<div id="middle">
<div id="inner">
<div id="target"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>