Dope Dope - 6 months ago 25
jQuery Question

Why isn't my Jquery closest function working

So I have this function:

var test = $('#currentCat').closest('div');
alert(test);


And here is the HTML

<div class="collapse" id="26">
<a href="#" class="list-group-item" id="currentCat">Hoodies (6)</a>
</div>


But instead of giving me HTMLDivElement I get Object and it's not working

Answer
var test = $('#currentCat').closest('div');

jQuery does not return DOM elements. It returns a jQuery object, which is also an array, which CONTAINS DOM elements.

Do this:

var $list = $('#currentCat').closest('div');
var element=$list[0]; // Get first item from the array
console.log(element);

Pro debugging hint:

Next time you have a question like this, examine the contents you're looking at.
Had you done a console.log(test), you could have seen it was an array (or array-like) structure.