2/1/2013 -

Why is javascript / jQuery not getting parentNode?

Given that I have an element like this:

<p class="ELP">2/1/2013 - <a id="EL3" class="ELLink" href="/Event htms/Event.cshtml?title=Okmulgee Public Schools County Professional Day&amp;explanation=Okmulgee Public Schools County Professional Day.&amp;dateString=2-1-2013">City Public Schools County Professional Day</a></p>

      

Why does this JavaScript / jQuery work ...:

$(".ELP").click(function (){
        var stringDate = $(this).text().substring(0, 8)
        console.log(stringDate)
    });

      

Console.log produces: 2/1/2013

... And this JavaScript / jQuery isn't working?

$(".ELLink").click(function (){
        var stringDate = $(this).parentNode.text().substring(0, 8)
        console.log(stringDate)
    });

      

.Log console does not produce anything due to JavaScript error: Uncaught TypeError: Cannot call method 'text' of undefined

Clearly what I can see is not "getting" the correct item, but why? Isn't the first parent node of my 'a' element the 'p' element? As far as I understand, there is no (at least not cross-browser / platform compatible) valid css selector for the element's direct parent node, or I would just use that.

What can't I see?

+3


source to share


5 answers


JQuery method called parent ()



$(".ELLink").click(function (){
        var stringDate = $(this).parent().text().substring(0, 8)
        console.log(stringDate)
    });

      

+7


source


As jQuery object doesn't have parentNode property.



var stringDate = $(this.parentNode).text().substring(0, 8);

      

+1


source


$(...)

does not return DOM elements, it returns an array-like object that refers to DOM nodes. DOM nodes have parentNode

. There are no jQuery instances.

If you need to select the immediate parents of the selected items, you can use parent()

:

$(this).parent().text()...

      

0


source


Why not use:

var stringDate = $(this).parent().text().substring(0, 8)

      

Since you are already using jQuery, you can use the parent function .

0


source


You need to use parent()

not parentNode

. Like this:

$(".ELLink").click(function (){
    var stringDate = $(this).parent().text().substring(0, 8)
    console.log(stringDate)
});

      

0


source







All Articles