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

后端 未结 3 1212
情歌与酒
情歌与酒 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: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";
    });
    

提交回复
热议问题