Nikhil Agrawal Nikhil Agrawal - 1 year ago 57
Javascript Question

jquery .closest() select itself when trying to access the closest upper div

Hello Actually What I want is to hide the immediate upper div of an div element if it is empty

So I written the code like this

if ($.trim($('#searchQuery').html()) == '') {

$('#searchQuery').closest("div").css("display", "none");

The element with the
id searchQuery
is itself is
so what it is doing it is hiding itself.

Anybody know what to do in this case why its behavior is like this??

Answer Source

See Jquery .closest() documentation.

Jquery .closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

1 .Begins with the current element

Your selector [.closest("div")] refers the current element #searchQuery

2. Travels up the DOM tree until it finds a match for the supplied selector

#searchQuery is the first element in DOM tree, which perfectly matched with the current selector [.closest("div")]


Here you can use .parent(), .prev() selector instead of using .closest().

Or you can use .closest() selector with .not() selector.