How do I get the class of an element when clicking on it?

  • 0
    How to get the class of an element when you click on it?

    <div class="block"></div>
    <div class="block" onclick="function()"></div>
    <div class="block"></div>

    As with a similar structure, when you click on a block, get its class with a number.
    (When pressed should output block [1])
    JavaScript Atticus Woodward, Apr 27, 2019

  • 3 Answers
  • 0
    if the collection has blocks then:

    const block = document.querySelectorAll ('. block')

    block.forEach ((bl, index) = & gt; bl.addEventListener ('click', () = & gt; console.log (bl.className, index)))
    Madeline Beck

  • 0

  • 0
    You can also explicitly set the number, especially if it is an id from a database table:

    <div class="block" data-id="10">[ 1 ]</div>
    <div class="block" data-id="15">[ 2 ]</div>
    <div class="block" data-id="21">[ 3 ]</div>

    const clickFunc = (event) => {
    const blockId =;
    .forEach((el) => el.addEventListener("click", clickFunc));

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!