0

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.

5120bee
  • 689
  • 1
  • 14
  • 36
  • Possible duplicate of [How to get class name through JavaScript?](https://stackoverflow.com/questions/39114858/how-to-get-class-name-through-javascript) – Obsidian Age Mar 28 '18 at 23:30
  • Uh, if you selected the element by that name you already know the name?! – Bergi Mar 28 '18 at 23:33

1 Answers1

2

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>
Paul
  • 2,086
  • 1
  • 8
  • 16