1

Im trying to get all elements that contain a class name also if the elements have multiple classes (in Javascript). For example:

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

So i now want all classes that contain the class "one". So in this case all of them. If i use getElementsByClassName i can only specify 1 class or i need to write the exact multiple classes there.

Any suggestions are really apreciated!

pepote
  • 313
  • 7
  • 21
  • Have you tried this? http://stackoverflow.com/questions/2727303/jquery-counting-elements-by-class-what-is-the-best-way-to-implement-this – Dan Wears Prada Mar 27 '17 at 15:50
  • Possible duplicate of [How to get element by class name?](http://stackoverflow.com/questions/17965956/how-to-get-element-by-class-name) – fingerprints Mar 27 '17 at 16:22

4 Answers4

2

It would have been easier (and faster) to try to write some code and test your question directly instead of asking in SO.

Or maybe reading the documentation for getElementsByClassName

[Sigh] you don't hace to specify the exact multiple classes. Running:

document.getElementsByClassName("one")

will give you an array with the four divs.

EduG
  • 108
  • 1
  • 1
  • 5
1

If you would like to get the full className of every element having a class, you can do it like this

// 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">
Ionut
  • 1,729
  • 4
  • 23
  • 50
0

The property you're looking for is 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);
AJ_
  • 3,787
  • 10
  • 47
  • 82
0

What you want should be 'one' , it will return all elements that have 'one' as class regardless other classes the element belongs to.

document.getElementsByClassName('one')

Just FYI for multiple classes

document.getElementsByClassName('one two three')
Nawwar Elnarsh
  • 1,049
  • 16
  • 28