Javascript 如何通过类名获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8538343/
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-08-24 06:25:40  来源:igfitidea点击:

How to get element by class name

javascripthtmlcssdom

提问by foshoeiyyy

I want to know if there is a way to getElementByClassName("classname").innerHTMLfunction or something to the equivalent of getElementById("ClassName").innerHTML.

我想知道是否有一种方法可以getElementByClassName("classname").innerHTML发挥作用或相当于getElementById("ClassName").innerHTML.

回答by Blender

You are missing an sin your function name. getElementsByTagNamereturns a collection of elements, of elements, which you need to iterate over:

s的函数名称中缺少一个。getElementsByTagName返回元素的集合,元素的集合,您需要对其进行迭代:

var elements = document.getElementsByClassName("classname");

for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = 'foo';
}

IE8 and below don't support getElementsByClassName, so you'll have to find a polyfill or use querySelectorAll(IE8).

IE8 及以下不支持getElementsByClassName,因此您必须找到 polyfill 或使用querySelectorAll(IE8)。

回答by Francesco Belladonna

I suggest you to use JQuery, where you can use directly CSS selectors (like .yourclass) to find all elements of a given class:

我建议您使用 JQuery,您可以在其中直接使用 CSS 选择器(如 .yourclass)来查找给定类的所有元素:

$('.yourclass').doWhatYouWant();

If you prefer not to use JQuery, you can use plain Javascript:

如果你不想使用 JQuery,你可以使用普通的 Javascript:

document.getElementsByClassName('my-fancy-class')

But be careful with IE8 incompatibility issue. As an alternative (slower but you can build more complex CSS selectors) you can use:

但要小心 IE8 不兼容问题。作为替代方案(较慢但您可以构建更复杂的 CSS 选择器),您可以使用:

document.querySelector('.cssSelector')

Which will return one elementresponding to your CSS selector, or

这将返回一个响应您的 CSS 选择器的元素,或者

document.querySelectorAll('.cssSelector')

Which will return multiple elements instead.

这将返回多个元素。

回答by Robert

You can do this using jquery

您可以使用 jquery 执行此操作

$('.className').html();

http://api.jquery.com/html/

http://api.jquery.com/html/

回答by Andrea Colleoni

If tou use jQuery you can get it as you would in a CSS selector so:

如果你使用 jQuery,你可以像在 CSS 选择器中一样得到它,所以:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>

then...

然后...

$('.classname').each(function() {
    // get html
    $(this).html();
    // set html
    $(this).html('something');
});

Notice you have also convenient way to manage innerHTML.

请注意,您还可以方便地管理innerHTML。