What\'s the native equivalent of jQuery\'s $.fn.has?
For example, how would you write the following code:
$(\"li\").has(\"ul\").css(\"background-color\",
I know this is an extremely late answer but here is an updated version of Lennholm's answer.
const has = (selector, sub) => {
const matches = Array.from(document.querySelectorAll(selector));
return matches.filter(match => match.querySelector(sub) !== null);
};
has("li", "ul").forEach(li => {
li.style["background-color"] = "red";
});
Since i don't use jQuery, I can not make not sure if has
selects all <li>
elements which are direct parents of <lu>
elements (like CSS selector li > ul
) or selects all <li>
elements having <lu>
elements under (like CSS selector li ul
). Chose the one you like;
Array.from(document.querySelectorAll("li ul")).reduce((r, e) =>
r.length ? (r[r.length - 1] === e.parentElement ? r : r.concat(e.parentElement)) : r.concat(e.parentElement), []
);
Thanks @Barmar's comment for the clarification.
I would basically do it the way the jQuery specification for .has()
describes it, i.e. filtering the collection by trying to select the required element from the descendants of each element:
var liElements = Array.from(document.querySelectorAll("li"));
var liElementsThatHaveUl = liElements.filter(function(li) {
return li.querySelector("ul");
});
liElementsThatHaveUl.forEach(function(li) {
li.style.backgroundColor = "red";
});