如何获取具有多个类的元素的类名,但只知道其中的一个

时间:2017-03-27 15:47:02

标签: javascript html

如果元素有多个类(在Javascript中),我也试图获取包含类名的所有元素。例如:

<div class="one two three four">
<div class="one two three">
<div class="one two">
<div class="one">

所以我现在想要所有包含类&#34;一个&#34;的类。所以在这种情况下所有这些。如果我使用getElementsByClassName,我只能指定1个类,或者我需要在那里写出确切的多个类。

任何建议都是非常苛刻的!

4 个答案:

答案 0 :(得分:1)

尝试编写一些代码并直接测试您的问题而不是在SO中询问会更容易(也更快)。

或者可以阅读getElementsByClassName

的文档

[叹气]你没有指定确切的多个班级。运行:

document.getElementsByClassName("one")

会给你一个包含四个div的数组。

答案 1 :(得分:0)

您正在寻找的属性是className。

HTML

<div id="myId" class="one">
    stuff 
</div>
<div id="myId" class="one two">
    stuff 
</div>

JS

var d= document.getElementById('myId');
alert(d.className);

答案 2 :(得分:0)

你想要的应该是&#39;一个&#39; ,它将返回所有具有&#39; one&#39;无论该元素属于哪个类,都可以作为类。

document.getElementsByClassName('one')

仅适用于多个班级

document.getElementsByClassName('one two three')

答案 3 :(得分:0)

如果你想得到每个有一个类的元素的完整className,你可以这样做

// list className of all elements containing the class 'two'
Array.from(document.querySelectorAll('.two')).forEach(function(element) {
  console.log(element.className);
});
<div class="one two three four">
<div class="one two three">
<div class="one two">
<div class="one">