0

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>

1
  • what do you mean by added dynamic? added using jquery ? Commented Oct 19, 2016 at 7:55

3 Answers 3

4

$('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>

Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

1

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
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.