纯JS中jQuery的contents()方法 [英] jQuery's contents() methods in pure JS

查看:683
本文介绍了纯JS中jQuery的contents()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在尝试执行以下代码而不导入jQuery库:

So I've been trying to do the following bit of code without importing the jQuery library:

$(".parent-class").contents().find(".child-class").css("color", "red");

我知道 .contents() 获取每个子项的子项jQuery文档中匹配元素(包括文本和注释节点)中的 元素,但我认为我不理解该描述的含义.我试过让.parent-class的孩子与:

let theChildren = document.querySelector('.parent-class').children;

,但这与.contents().find(".child-class")的作用不同.

but this doesn't do the same thing as .contents().find(".child-class") does.

编辑:根据评论的要求,我进行了

EDIT: As requested in the comments I've made a new question as this one seems to not be specific enough.

推荐答案

contents()主要在jQuery中用于需要选择文本节点的情况.在第一个代码示例中,您根本不需要它,因为使用find()选择带有类的元素. jQuery的这些行将达到相同的目的:

contents() is primarily used in jQuery when you need to select text nodes. In the first code sample you have it's not needed at all, as you use find() to select elements with a class. These lines of jQuery would serve the same purpose:

$(".parent-class").find(".child-class").css("color", "red");
$(".parent-class .child-class").css("color", "red");

在普通JS中,这将是:

In plain JS this would be:

document.querySelectorAll('.parent-class .child-class').forEach(el => el.style.color = 'red');

请注意querySelectorAll().这将返回一个nodeList,您需要对其进行迭代以以与jQuery代码相同的方式更新样式.

Note querySelectorAll() there. This will return a nodeList which you need to iterate through to update the style in the same way the jQuery code does.

没有与contents()等效的显式JS,因为您手动遍历以找到要定位的节点,或者使用querySelector()getElementByX()等定位元素.

There is no explicit JS equivalent of contents() because you traverse manually to find the nodes you want to target, or use querySelector(), getElementByX() etc to target the elements.

这篇关于纯JS中jQuery的contents()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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