Reputation: 709
To get elements using a class name, document.getElementsByClassName()
can be used.
But is there a function in JavaScript to get the actual name of the class itself?
Example:
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].innerHTML;
<div class="myClass">Hello</div>
<div id="result"></div>
printResult will just print out "Hello". What if I want the result to print out the string "myClass" which is the actual class name?
I tried classElement[0].className.innerHTML
but it returns undefined
.
Upvotes: 0
Views: 40
Reputation: 2076
className
is a property of the dom node containing the classes of the element.
You don't need to add innerHTML
, which is another property of the dom node and returns/sets the html content of the corresponding element.
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].className;
<div class="myClass">Hello</div>
<div id="result"></div>
Upvotes: 2