qadenza
qadenza

Reputation: 9293

detect click on element with a child inside

$('.parent').on('click', function(e) {
  if (e.target.matches('.inside')) {
    console.log('inside');
  } else {
    console.log('title');
  }
});
.parent {
  background: lightgreen;
}

.inside {
  background: silver;
}

.title {
  background: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
  <div class='inside'>
    <div class='title'>lorem</div>
  </div>
  <br>
</div>

Click on inside and you'll get title in console.

How to get inside regardles a title is inside or not?

Upvotes: 0

Views: 60

Answers (3)

Jamie Bradley
Jamie Bradley

Reputation: 669

Okay take a look at this and see if it works for you?

https://codepen.io/jamie-endeavour/pen/GPjzRq?editors=1011

$('.parent').on('click', function(e) {
  var $target = $(e.target);

  if ($target.hasClass('inside') || $target.parent().hasClass('inside')) {
    console.log('inside');    
  } else {
    console.log('not inside');
  }
});

I am checking if the user has clicked on the element with the 'inside' class or if the child element belongs to the 'inside' element.

Hope this helps?

Upvotes: 1

BenG
BenG

Reputation: 15154

You need to check if the target has a parent .inside :-

$('.parent').on('click', function(e) {
  if ($(e.target).parents('.inside').length) {
    console.log('inside');
  } else {
    console.log('title');
  }
});
.parent {
  background: lightgreen;
}

.inside {
  background: silver;
}

.title {
  background: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
  <div class='inside'>
    <div class='title'>lorem</div>
  </div>
  <br>
</div>

Upvotes: 1

Abhay Maurya
Abhay Maurya

Reputation: 12277

Please note that HTML works in layer so if title is going to be inside "inside", you can just target title for click as inside is always "inside" it.

$('.title').on('click', function(e){
	console.log('inside');
});
.parent{
background:lightgreen;
}
.inside{
background:silver;
}
.title{
background:gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
<div class='inside'>
<div class='title'>lorem</div>
</div>
<br>
</div>

Upvotes: 0

Related Questions