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

后端 未结 3 1178
情歌与酒
情歌与酒 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:46

    Since i don't use jQuery, I can not make not sure if has selects all

  • elements which are direct parents of elements (like CSS selector li > ul) or selects all
  • elements having 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.

提交回复
热议问题