user007
user007

Reputation: 3243

jQuery - attr('class') getting parent class

I am trying to get class of an element, but it shows its parent class if current element class is empty.

I just want to check if current element has class if not do nothing but dont show parent class

$('*').click(function(){
    var class_of_el = $(this).attr('class').replace('test', '').replace('test2', '');
    alert(class_of_el);
});

here is the fiddle :http://jsfiddle.net/howtoplease/cpENU/

Upvotes: 0

Views: 126

Answers (5)

A.T.
A.T.

Reputation: 26312

you should stop event to bubble to outer elements-

you can do something like this

$('*').click(function(event){
    event.stopPropagation();  // This will stop bubbling of event
    var class_of_el = $(this).attr('class').replace('test', '').replace('test2', '');
    alert(class_of_el);
});

http://jsfiddle.net/cpENU/6/

Upvotes: 1

agelber
agelber

Reputation: 304

As said by winterblood, the event is progating to the parent element because you selected every element on the page.
However, I would also like to add that if your objective is to check for a specific class, you can use hasClass instead of parsing the class attribute.

$('*').click(function(evt) {
    evt.stopPropagation();
    var isTest = $(this).hasClass('test');
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

It could be a bad idea to register click event handlers to all elements in the document and to prevent event propagation from them.

$(document).on('click', '*', function(e){
    if(e.target == this){
        console.log($(this).attr('class'))
    }
})

Demo: Fiddle

Upvotes: 1

Nishu Tayal
Nishu Tayal

Reputation: 20830

jQuery('*') selects all elements, That's why you are getting parent element class name also.

When you add null check with class, you can see, it returns value for each element. i.e.

$('*').click(function(){
    var class_of_el = $(this).attr('class') != undefined? $(this).attr('class').replace('test', '').replace('test2', '') : 'empty';
    alert(class_of_el);
});

Here is the demo.

Upvotes: 1

Ken Herbert
Ken Herbert

Reputation: 5236

The problem is that the event is propagating.

Try this:

$('*').click(function(evt){
    evt.stopPropagation();
    var class_of_el = $(this).attr('class').replace('test', '').replace('test2', '');
    alert(class_of_el);
});

Now when clicking an element without a class, nothing happens, but if you click an element with a class it will be alerted. jsFiddle

Upvotes: 3

Related Questions