Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Uncaught TypeError: Object #<HTMLElement> has no method 'parent'

Tags:

jquery

Something is wrong with my code. Chrome code spectrator say that there is probmel in line number 21, problem like this: Uncaught TypeError: Object #<HTMLElement> has no method 'parent'. This is jQuery code:

  $('.plus').click(function(){
    if ($(this).text() == "+"){    /* 1 IF       */
        $(this).text("-");

        if (! ($(this).parent().next().is('ul'))){            /* 2 IF */
        var element_id = $(this).parent().attr('id') 
        var id = '#' + element_id
        var url = "/accounts/profile/thingh_update/" + element_id + "/";

        $.getJSON(url, function(data){
        var items = []

        $.each(data, function(index, value) {    if(value.pk)        
        items.push('<li id="' + value.pk + '">' + value.fields.title + '&nbsp;&nbsp;<span class="plus">+</span></li>');});

        $('<ul/>', {
        html: items.join('')
        }).insertAfter(id); })
        } else {(this).parent().next().children().show()}    /* 2 ELSE */
      } else {$(this).text('+').parent().next().hide()}    /* 1 ELSE */
  })    
}) 

My html looks like this:

<ul>
    <li id="3"><a href="/my/proper/url/">this is for eat</a>&nbsp;&nbsp;
    <span class="plus">+</span></li> <!-- after clickin this I get proper json data, and "+" is cahnged to "-", and the next "<ul>" element appear -->
    <ul>
    <li id="4">fishes&nbsp;&nbsp;
    <span class="plus">+</span></li>
    </ul>
</ul>

And when I click on "-" in first "li" element and then again on "+" i get:

Uncaught TypeError: Object #<HTMLElement> has no method 'parent'

Maybe i missed something obvious, but I am not advanced in jQuery yet. I ask for some tolerance for beginner and any sugegestions of where could I do mistake. Thanks.

like image 528
krzyhub Avatar asked Dec 02 '22 01:12

krzyhub


2 Answers

On this line:

} else {(this).parent().next().children().show()}

You are missing the $ before (this), which means you are trying to call parent() on a DOM element, rather than a jQuery object.

like image 120
James Allardice Avatar answered May 01 '23 19:05

James Allardice


} else {(this).parent().next().children().show()}

You forgot the $ before (this). It should be:

} else {$(this).parent().next().children().show()}
like image 37
Rocket Hazmat Avatar answered May 01 '23 17:05

Rocket Hazmat