简体   繁体   中英

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 div so what it is doing it is hiding itself.

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

A few things:

  • Use .text() instead of .html() to avoid getting HTML tags which wont be removed in the trim.
  • Use .hide() instead of .css("display", "none") .
  • Use .parent() for immediate parent.

Example solution:

$('#searchQuery').parent().hide();

Or you could use :not(..) .

$('#searchQuery').closest("div:not(#searchQuery)").hide();

http://api.jquery.com/not-selector/

It selects itself because it

Begins with the current element

http://api.jquery.com/closest/

Or you could use .parents(...) (note the s on the end). This travels trough the DOM tree until it finds the selector you pass in the argument.

http://api.jquery.com/parents/

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")]

Updated:

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

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

Why not simply this ?

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

As an aside, as trgraglia noticed, you shoud also use hide :

$('#searchQuery').parent("div").hide();

Depends what you mean by "upper div"

If it's the previous sibling:

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

or the parent:

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

使用.parent()而不是最接近:)

This is an old question, but I ran into the same issue today and solved it by doing :

$myelement.parent().closest('div');

this will ignore $myelement and look above it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM