jQuery的"$ .fn.has"的本机等效项是什么? [英] What is the native equivalent to jQuery's "$.fn.has"?

查看:72
本文介绍了jQuery的"$ .fn.has"的本机等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery的 $.fn.has 的本机等效项是什么?

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", "red");

使用普通JavaScript吗?

In vanilla JavaScript?

注意::这个问题是关于has函数而不是contain函数的问题.

NOTE: This question is about the has function and not the contain function.

推荐答案

我基本上会按照.has()的jQuery规范描述它的方式进行操作,即通过尝试从每个后代中选择所需的元素来过滤集合元素:

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";
});

这篇关于jQuery的"$ .fn.has"的本机等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆