Thinh Phan
Thinh Phan

Reputation: 655

how to detect an element that is clicked from many the same element

I have a lot of elements that have the same tags as follow:

<ul>
  <li>
    <a>1</a>
    ...
  </li>
  <li>
    <a>2</a>
    ...
  </li>
  <li>
    <a>3</a>
    ...
  </li>
  ...
</ul>

User can click on any element. How can I detect the element that user click? (I don't know the number of element before. I can be five or there or any number).

Thanks

Upvotes: 1

Views: 55

Answers (3)

Adil
Adil

Reputation: 148130

You can use $(this) or this to refer to source of event.

$('a').click(function(){
  alert($(this).text());
  alert(this.innerText);
});

It is better to use a class to be specific, so that the event is bind with intended elements instead of any a on the page. You can assign a class to elements on which you want to bind click event and use class selector to bind the event.

<a class="myclass">1</a>

$('.myclass').click(function(){
    alert($(this).text());
    alert(this.innerText);
});

Upvotes: 4

nix
nix

Reputation: 3302

You can get the clicked element using this. For example:

$('a').click(function(){
    alert($(this).text()); //displays the clicked element's text.
});

Upvotes: 3

PSL
PSL

Reputation: 123739

Binding on anchor tag

$('ul li a').on('click',function(){

    alert($(this).text()); //This will give the text
    alert(this.id); //This will give you the id if you have id for anch tag.

});

Binding on li

$('ul li').on('click',function(){

    alert($(this).text()); //This will give the text of anchor ta in your case
    alert($(this).index()); //This will give you the index of li with respect to its siblings.

    });

Upvotes: 1

Related Questions