1

I have added click event listener on multiple elements in jQuery which works fine:

$('#element1, #element2, #element3, #element4').on('click', function(){
  // do something with the clicked element
});

Now I would like to find out which element is being clicked. How can I do that? Thank you very much.

1

3 Answers 3

2

You can get it by following

$('#element1, #element2, #element3, #element4').on('click', function(){
       var ID = $(this).attr('id'); 
       alert('you clicked on #' +ID);
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can either use this or check the target property of the passing event of the event handler function:

Using this:

$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log('The id of the clicked button is: ' +this.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element1">Button1</button>
<button id="element2">Button2</button>
<button id="element3">Button3</button>
<button id="element4">Button4</button>

Using Event.target:

$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log('The id of the clicked button is: ' +event.target.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element1">Button1</button>
<button id="element2">Button2</button>
<button id="element3">Button3</button>
<button id="element4">Button4</button>

Comments

1

You can do it with event.target

$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log(event.target)
});

Read this for more understanding

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.