JQuery - Uncaught TypeError: Object # <HTMLElement> does not have a 'parent' method

Something is wrong with my code. The Chrome code spectrometer says there is a problem in line number 21, the problem is 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 “-” in the first element “li” and then again on “+”, I get:

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

I might have missed something obvious, but not yet advanced in jQuery. I ask for some tolerance for newbies and any errors in where I might be wrong. Thanks.

+4
source share
2 answers

In this line:

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

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

+16
source
 } else {(this).parent().next().children().show()} 

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

 } else {$(this).parent().next().children().show()} 
+2
source

All Articles