Jan Kowalski
Jan Kowalski

Reputation: 205

How to detect clicked element added dynamic using jquery?

How can I detect clicked element in code like this:

HTML:

<div class="foo">
  <a href=""><b>Foo</b></a>
</div>   
<div class="bar">
  <a href=""><b>Bar</b></a>
</div>

jQuery:

$('body').on('click', '.foo, .bar', function (e) {     
   if (detectElement == '.bar') {
     //
   }
}

I try $('this') but returned body not clicked element. I try also e.target but I want get main element (.foo or .bar), not <a> / <b>

Upvotes: 0

Views: 1072

Answers (3)

Satpal
Satpal

Reputation: 133403

You could use .is()

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

and The selector is not correct instead use event.currentTarget, , when you use $('this') is Element Selector (“element”) since you have no HTML element as this the condition does't works.

The current DOM element within the event bubbling phase.

$('body').on('click', '.foo, .bar', function (event) {
    if ($(event.currentTarget).is('.bar')) {
        //Your code
    }
});

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

$('this') isn't right. this is variable that contain clicked element. You can't use it as string. Use .hasClass() to check element has specific class name.

$('body').on('click', '.foo, .bar', function (e) {
    if ($(this).hasClass('bar')) {
        // code
    }
});

$('body').on('click', '.foo, .bar', function (e) {
    if ($(this).hasClass('bar'))
        console.log("is .bar");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
  <a href="#"><b>Foo</b></a>
</div>
<div class="bar">
  <a href="#"><b>Bar</b></a>
</div>

Upvotes: 4

David R
David R

Reputation: 15639

Use the currentTarget attribute of the event callback.

$('body').on('click', '.foo, .bar', function (e) {
  $(e.currentTarget).hasClass('foo') {
    alert('Foo has been clicked');
  }

  $(e.currentTarget).hasClass('bar') {
    alert('Bar has been clicked');
  }
});

Hope this helps!

Upvotes: 1

Related Questions