Javascript 按标签和类获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12685963/
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 and class
提问by Martin
I have a script
我有一个脚本
var firstImg = row.getElementsByTagName('img')[0];
and later
然后
if (x){ firstImg.src='/images/checked.png'; }
I'd like to define that the img should be of class='something'
我想定义 img 应该是 class='something'
(Get first img with class='something') 10x in advance!
(使用 class='something' 获取第一个 img)提前 10 倍!
回答by geekman
Use the
使用
querySelectorAll('img.classname')[0]
this returns first image with class set to class name. However jQuery is better!!
这将返回类设置为类名的第一个图像。但是jQuery更好!!
$('img.classname')
回答by alex
Just set it...
就这样设置...
firstImg.className += "something";
...or...
...或者...
firstImg.classList.add("something");
If you can get away with not supporting older browsers.
如果您可以避免不支持旧浏览器。
Further Reading(disclaimer: link to my own blog).
进一步阅读(免责声明:链接到我自己的博客)。
If you're intending to getelements with a certain class name, you can use...
如果您打算获取具有特定类名的元素,您可以使用...
document.getElementsByClassName("something");
...or...
...或者...
document.querySelectorAll(".something");
Keep in mind getElementsByClassName()
isn't in <= IE8.
请记住getElementsByClassName()
不在 <= IE8 中。
You can use...
您可以使用...
var getElementsByClassName(nodeList, className) {
var i, results = [];
for (i = 0; i < nodeList.length; i++) {
if ((" " + nodeList[i].className + " ").indexOf(" " + className + " ") > -1) {
results.push(nodeList[i]);
}
}
return results;
}
Of course, it's super simple if you're using jQuery...
当然,如果你使用 jQuery,那是非常简单的......
$(".something");
回答by Roman
this selects the first img
with class='something':
这将选择第一个img
class='something':
var firstImg = $('img.something')[0];
回答by xdazz
If you could not throw away the old browsers, then you need a loop.
如果你不能扔掉旧的浏览器,那么你需要一个循环。
var imgs = row.getElementsByTagName('img'),
some_class = 'something',
i, first_img;
for (i = 0; i < imgs.length; i++) {
if ((' ' + imgs[i].className + ' ').indexOf(' ' + some_class + ' ') > -1) {
first_img = imgs[i];
break;
}
}