javascript GetElementsByTagName 与类选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19246954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:52:22  来源:igfitidea点击:

GetElementsByTagName with the class selector

javascript

提问by Alnedru

I have a question regarding the GetElementsByTagName, i would like to retrieve all elements which are TD but also have class name "MyClass" and which do not have an attribute height.

我有一个关于 GetElementsByTagName 的问题,我想检索所有 TD 但也有类名“MyClass”并且没有属性高度的元素。

I do the following:

我执行以下操作:

document.getElementsByTagName("TD")

document.getElementsByTagName("TD")

and it works. When i do

它有效。当我做

document.getElementsByTagName("TD.MyClass:not[height]")

document.getElementsByTagName("TD.MyClass:not[height]")

it doesn't work

它不起作用

How do I make it possible withouth using JQuery or can i retrieve first all TD's and then apply some filter on the set of td's?

如何在不使用 JQuery 的情况下使其成为可能,或者我可以首先检索所有 TD,然后在一组 td 上应用一些过滤器?

Any help?

有什么帮助吗?

回答by James Donnelly

This is something you'd use document.querySelectorAll()for. It's worth noting that you'd need to use brackets around that :not[height], too, otherwise your selector isn't valid:

这是你会用的东西document.querySelectorAll()。值得注意的是,您还需要在 that 周围使用方括号:not[height],否则您的选择器无效:

document.querySelectorAll("TD.MyClass:not([height])");

回答by lukaleli

you can use document.querySelectorAllwhich returns collection of html nodes that apply to given selector

您可以使用document.querySelectorAllwhich 返回适用于给定选择器的 html 节点集合

document.querySelectorAll('td.myClass'); // will return array of all tds with given class