javascript 通过标签名和类名获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18242171/
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
Get element by tag name and class name
提问by Leke
(in vanilla JavaScript) I was wondering if the was an easy way to do something like
(在 vanilla JavaScript 中)我想知道这是否是一种简单的方法来做类似的事情
x = document.getElementsByTagName('span') && getElementsByClassName('null');
To return all 'span' elements that have the class name 'null'?
返回所有类名为“null”的“span”元素?
I thought it might have been something like:
我认为它可能是这样的:
x = document.getElementsByTagName('span');
x = x.getElementsByClassName('null');
// or
x = document.getElementsByTagName('span').getElementsByClassName('null');
But that didn't seem to work out.
但这似乎并没有奏效。
Is this possible or will I have to iterate through x popping anything that returns false for .class='null'?
这是可能的还是我必须遍历 x 弹出任何为 .class='null' 返回 false 的东西?
Thanks.
谢谢。
回答by SLaks
The DOM does not provide any APIs for filtering NodeLists.
DOM 不提供任何用于过滤 NodeList 的 API。
Instead, you can use CSS selectors:
相反,您可以使用 CSS 选择器:
var x = document.querySelectorAll('span.null');