Misha Moroshko
Misha Moroshko

Reputation: 171321

jQuery .parent() does not work

Why the following code fails with:

Error: class_a_jquery_objects[0].parent is not a function

?

HTML:

<div>
    <div class='a b'></div>
    <div class='b c'></div>
    <div class='c a'></div>
</div>    
<div id='log'></div>

JS:

$(function() {
    var class_a_jquery_objects = $(".a");

    $("#log").append(class_a_jquery_objects.length + "<br />");
    $("#log").append(class_a_jquery_objects[0] + "<br />");
    $("#log").append(class_a_jquery_objects[0].parent() + "<br />");
});

Upvotes: 10

Views: 14875

Answers (2)

Artem Barger
Artem Barger

Reputation: 41222

You need to wrap it with JQuery object

   $("#log").append($(class_a_jquery_objects[0]).parent() + "<br />");

Upvotes: 1

kgiannakakis
kgiannakakis

Reputation: 104168

class_a_jquery_objects[0] is a DOM element and not a jQuery object. You can't call jQuery methods with it. You need to first wrap it in a jQuery object:

$(class_a_jquery_objects[0]).parent()

Upvotes: 22

Related Questions