getElementsByClassName返回包含指定名称的类名 [英] getElementsByClassName returns class names that contain specified name

查看:748
本文介绍了getElementsByClassName返回包含指定名称的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用document.getElementsByClassName('example'),但它也返回指定参数是子字符串的类。
例如,它还将返回一个元素,其中类名是other example。有没有办法解决这个问题?

I am using document.getElementsByClassName('example'), but it also returns classes where the specified parameter is a substring. For example, it would also return an element where the classname is 'other example'. Is there a way to fix this?

推荐答案

您正在为示例类选择任何元素。 class =other example表示元素同时具有exampleother。

There's nothing broken; you're selecting for any elements with the "example" class. class="other example" means an element has both "example" and "other".

如果要仅使用 检索元素,而您的浏览器支持 querySelectorAll *,您可以这样使用:

If you want to retrieve elements with only one class, and your browser supports querySelectorAll*, you can use that, like so:

var exact = document.querySelectorAll('[class="example"]');

for ( var i = 0; i < exact.length; ++i )
  exact[i].style.fontWeight = 'bold';

<p class="example">example only</p>
<p class="other example">... and other</p>

* 如果它也支持 getElementsByClassName

这篇关于getElementsByClassName返回包含指定名称的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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