Reputation: 313
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!
Upvotes: 1
Views: 4432
Reputation: 1749
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">
Upvotes: 1
Reputation: 128
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.
Upvotes: 2
Reputation: 1069
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')
Upvotes: 0
Reputation: 3977
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);
Upvotes: 0