Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use event.target to get the class value?

Tags:

jquery

i have a DOM element with class='tag'.

i want to check if the class value is tag and alert a message if it's true.

i wrote:

    $("#thread").each(function(event) {
        if(event.target.class == 'tag') alert('yes');
    });

but it didn't work. you can get the id with event.target.id but not the class with this code? what are all the values you can have after event.target?

like image 649
ajsie Avatar asked Jan 24 '10 20:01

ajsie


People also ask

How do you find the class on an event target?

To check if event. target has specific class, call the classList. contains() method on the target object, e.g. event. target.

What is event target value?

event. target gives you the element that triggered the event. So, event. target. value retrieves the value of that element (an input field, in your example).


1 Answers

At first, the event argument work only for event handlers, and you are using the $.each method.

I don't really think that you want/need to use the $.each method, since you are using an #id selector, and id's should be unique.

To check if an element contains an specific class you can use the hasClass method:

if ($("#thread").hasClass('tag')) {
  //...
}

Also if you have a DOM element, to get it's class attribute, you should access it with className instead class, that's because class is a future reserved word in JavaScript, the same thing happens with other attributes like for, should be accessed as htmlFor...

like image 70
Christian C. Salvadó Avatar answered Sep 18 '22 15:09

Christian C. Salvadó