简体   繁体   中英

How to select the current element together with parents of a certain class?

I have something like this:

body-viewport
   div-page.active
    div-panel
     div-page
     div-page
     div-page
     div-page.active //start here

Question:
Is there an easy way in query to select all active-pages if I start from the bottom element?

This would work, but...

$('.div-page-active').closest('.body-viewport').find('.div-page-active').doSomething

Thanks for help!

$('.div-page-active').closest('.body-viewport').andSelf()

And Self:

Add the previous set of elements on the stack to the current set.

So starting from the bottom element, which I'll assume you've received in an event handler and so I'll call this (raw element):

If you want all other .div-page.active elements anywhere under the closest .body-viewport , I think your expression is pretty much the best way:

$(this).closest(".body-viewport").find(".div-page.active");

If you only need .div-page.active elements that are ancestors of this (not siblings or cousins, etc.), then you'll have to write a loop, jQuery doesn't have a "find me all ancestors matching selector X and stop on a match of selector Y". Eg, something like ( live example ):

$("#target").click(function() {
  var done = false;
  $(this).parents().filter(function() {
    var $this;

    if (done) {
      return false;
    }

    $this = $(this);
    if ($this.hasClass("body-viewport")) {
      done = true;
      return true;
    }
    else {
      return $this.hasClass("div-page") && $this.hasClass("active");
    }
  }).add(this).css("color", "green");
  display("Matches turned green.");
  return false;
});

In that example, when you click the bottommost .div-page.active , it turns that one, the .div-page.active a couple of levels up, and the .body-viewport green. Like this (matches shown in bold below, can't do color on SO), note that I added an unrelated .div-page.active and a cousin, to show how they aren't included:


  -- ancestor, should be included
  div-panel
   div-page
   div-page
   div-page
    -- click me
  div-page active -- cousin, should NOT be included
body-viewport
 div-page active -- unrelated, should NOT be included

尝试

$(this).siblings(".div-page-active").doSomething();

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