Pejman
Pejman

Reputation: 2636

Select descendants, except of one child

Let’s say I have this HTML:

<div class="par">
  <div class="s1">
    <a href="#" class="s1">link</link>
  </div>
  <div class="s8">
    <a href="#" class="s1">link</link>
    <div class="s1">
      <a href="#" class="s1">link</link>
    </div>
  </div>
  <div class="ds44">
    <a href="#" class="s1">link</link>
  </div>
  <span class="t">This is text</span>
  <div class="thisOne">
    <a href="#" class="s1">link</link>
  </div>
</div>

now I want to call this function:

function aFn(){
  alert('Omid');
}

by clicking on any elements in <div class="par"> except <div class="thisOne"> and its children. How can I do that?

Upvotes: 1

Views: 82

Answers (2)

Ry-
Ry-

Reputation: 224857

Handle click on .par and check e.target.

For example,

$(".par").on("click", function(e) {
    if ($(e.target).closest(".thisOne").length) {
        return;
    }

    …
});

Okay, that worked.

Upvotes: 1

Jason P
Jason P

Reputation: 27012

Assign a click handler to .par, then assign one to .thisOne that prevents the click from bubbling to .par.

$('.par').click(aFn);

$('.thisOne').click(function(e) {
    e.stopPropagation();
});

Upvotes: 2

Related Questions