querySelectorAll:操纵节点 [英] querySelectorAll: manipulating nodes

查看:87
本文介绍了querySelectorAll:操纵节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知, querySelector 返回一个真正的可更改元素,而 querySelectorAll 返回一个非实时静态节点集。

As far as I have understood, querySelector returns a real changeable element while querySelectorAll returns a non-live Static Node Set.

我想调整适合特定选择器的所有元素的样式。它适用于带有 querySelector 的第一个元素,但不适用于带有 querySelectorAll 的所有匹配元素。我猜这是因为节点集是非实时的。

I want to adjust the style of all elements fitting to a specific selector. It works fine for the first element with querySelector, but not for all matching elements with querySelectorAll. I guess that's because the node set is non-live.

有解决方法吗?或者我错过了什么?

Is there a workaround? Or am I missing something?

推荐答案

问题是 querySelector 返回单个节点。 querySelectorAll 返回一组节点(live-ness表示如果更新它们,则不会删除集合中的元素)。你需要在匹配的每个元素上设置一个样式,可能是一个循环 - 你不能只为它们设置一次属性。

The problem is that querySelector returns a single node. querySelectorAll returns a set of nodes (the live-ness means the elements in the set won't be removed if you update them). You need to set a style on each of the elements matched, probably with a loop -- you can't just set a property once for all of them.

所以,你可能需要这样做:

So, you probably need to do something like this:

var nodes = document.querySelectorAll('div.foo');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].style.color = 'blue';
}

这篇关于querySelectorAll:操纵节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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