jquery nodename returning undefined
Asked Answered
C

2

35

This code isn't for anything in particular. I'm just trying to successfully get the tagName or nodeName of an element. However, when I run the following code, I always get an alert saying "undefined". I'm wondering if it's because this function executes when the document is ready? Is there a different place I should be doing this? Or is it probably my other javascript code conflicting somehow (I would doubt).

 $(document).ready(function(){
        $('#first').hover(function() {
            alert($('#last').nodeName);
        });
    });
Cloaca answered 5/5, 2010 at 2:11 Comment(0)
M
57

You are trying to access a non-member of the jQuery object. Use one of these DOM element accessors to retrieve these properties:

$( '#last' ).get(0).nodeName

OR

$( '#last' )[0].nodeName

OR

document.getElementById( 'last' ).nodeName

Mickeymicki answered 5/5, 2010 at 2:12 Comment(2)
I don't think this works anymore and has been depreciated. Steven's answer worked fine: .prop("nodeName"))Boater
Two comments for @newUserNameHere: (1) The answer does work and the functions used are not deprecated. (2) Note the difference between "deprecated" (correct) and "depreciated" (incorrect), as discussed in this other Stack Exchange question.Ayeaye
R
65

Use the prop() of jQuery:

alert($('#last').prop("nodeName"));
Roxane answered 1/3, 2012 at 6:2 Comment(0)
M
57

You are trying to access a non-member of the jQuery object. Use one of these DOM element accessors to retrieve these properties:

$( '#last' ).get(0).nodeName

OR

$( '#last' )[0].nodeName

OR

document.getElementById( 'last' ).nodeName

Mickeymicki answered 5/5, 2010 at 2:12 Comment(2)
I don't think this works anymore and has been depreciated. Steven's answer worked fine: .prop("nodeName"))Boater
Two comments for @newUserNameHere: (1) The answer does work and the functions used are not deprecated. (2) Note the difference between "deprecated" (correct) and "depreciated" (incorrect), as discussed in this other Stack Exchange question.Ayeaye

© 2022 - 2024 — McMap. All rights reserved.