How to recover the class of a div by clicking on it?

Asked

Viewed 73 times

1

Several gero divs over time with a code Javascript, would like to retrieve the class of those Ivs by clicking on them. Or retrieve some other parameter to use in a comparison.

2 answers

3

You can use the this.className, or this.classList See the example below.

document.querySelectorAll(".btn").forEach(function(elem,idx){
 elem.onclick = click
 })
 
 function click(){
    /// neste contexto `this` é o elemento que foi clicado
    console.log( this.className );
    
    /// voce ainda pode utilizar o classList
    ///  que contem metodos como:
    ///  contains()
    ///  add()
    ///  remove()
    
    /// verificando se na lista de classes do elemento clicado contem a classe 'btn-1'
    console.log( "contains btn-1" , this.classList.contains('btn-1') );
   /// foreach na lista de classes
   this.classList.forEach(function(cls,idx){
       console.log('foreach', idx, cls);
   })

}
<div class='btn btn-1'>btn 1</div>
<div class='btn btn-2'>btn 2</div>
<div class='btn btn-3'>btn 3</div>

1

Brought a small example to retrieve the attribute className of the clicked object.

function recuperarClasse(obj) {
        alert(obj.className);
}
<span class="minhaClasse" onclick="recuperarClasse(this)">Clique aqui!</span>

By clicking on the span "Click here!" an alert will be displayed with the class of object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.