What is the native equivalent to jQuery's “$.fn.has”?

后端 未结 3 1179
情歌与酒
情歌与酒 2021-01-27 11:51

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\",         


        
相关标签:
3条回答
  • 2021-01-27 12:31

    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";
    });
    
    0 讨论(0)
  • 2021-01-27 12:46

    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.

    0 讨论(0)
  • 2021-01-27 12:51

    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";
    });
    
    0 讨论(0)
提交回复
热议问题