2

I am simply trying to find out if the parent of the A (i.e. the P) has a class called some_class defined on it. I will then use the true/false result in a conditional.

I have a simple structure:

<div class="things">
    <p class="some_class">
        <a href="something">Link One</a>
    </p>
</div>

And some jQuery script:

$(function() {
    $('.things a').click(function(e) {    
        e.preventDefault();    
        alert($(e.target).parent()[0].nodeName); //works, displays "P"
        alert($(e.target).parent()[0].hasClass('some_class').toString()); //No output
        });
    });

The call to the second alert() does nothing - no alert box is displayed at all.

What am I doing wrong?

A JSFiddle is here

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
Zabba
  • 64,285
  • 47
  • 179
  • 207

3 Answers3

6
alert($(e.target).parent()[0].hasClass('some_class').toString())

in the line above you converted your Jquery Object back to a HTML DOM Object. Therefore the hasClass method does not exist for $(e.target).parent()[0].

Remove the [0]

alert($(e.target).parent().hasClass('some_class').toString())

Here is your fiddle that I modified http://jsfiddle.net/LVerN/5/

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • @Zabba... This is a link to an old question I answered and it should give you some insight on the difference between jQuery objects and HTML DOM Objects. http://stackoverflow.com/questions/4069982/document-getelementbyid-vs-jquery/4070010#4070010 – John Hartsock Oct 13 '11 at 17:05
  • Thanks! Also using `$(this)` works. Time to read up on jQuery again! – Zabba Oct 13 '11 at 17:33
1

hasClass() is going to return a boolean value of true or false

$(e.target).parent()[0].hasClass() 

Will return error because the object at index zero is not a jQuery object. So you'll want to remove the [0]

brenjt
  • 15,997
  • 13
  • 77
  • 118
1

I have updated the jsFiddle

<div class="things">
    <p class="some_class">
        <a href="something">Link One</a>
    </p>
</div>

$(function() {
    $('.things a').click(function(e) {    
        e.preventDefault();    
        //alert($(e.target).parent().nodeName); //Shows "undefined". wtf
        alert($(e.target).parent()[0].nodeName); //works
        alert($(this).parent().hasClass('some_class').toString()); //No output
    });
});
Wazy
  • 8,822
  • 10
  • 53
  • 98