Question

I've got the following jQuery expression, Inside the function I need a reference to the object that was clicked, is there a way to do this?

$('#tagList li').click(function() {
  /* contents */
});
Was it helpful?

Solution

Use

$(this)

OTHER TIPS

you can use the return value

$("#tagList li").bind("click", function(e) {
    alert(e.currentTarget + ' was clicked!');
});

or if you want, you can simple point to the object in jQuery mode

$("#tagList li").bind("click", function(e) {
    alert($(this) + ' was clicked!');
});

if you're new to jQuery, I strongly suggest you to see some screencasts from Remy Sharp in jQuery for Designers, they are great to understand a little bit of how jQuery works, and better yet, how to use the console.log() in order to see the objects that you can use!

Yes, the this keyword references the DOM element that was clicked. You can "wrap" it like this:

$(this)

This will allow you to treat it as a jQuery object.

The this keyword is what you are looking for. Often you will want to apply the jQuery function to this to do your job. Example:

$('#tagList li').click(function() {
  $(this).css({ color: 'red' });
});

Adding a new answer that will cover more use cases, specifically when you want to use arrow functions.

It's also recommended that you don't add a JS click to an li element. Instead you should use a button or anchor (something clickable) nested inside this element.

Since the element that you click could be a child, you need to make sure you target the correct element.

In my example, I will be assigning the click to a button inside the li as well as a class on it. The markup will simply be:

<ul id="taglist">
  <li><button class="tag-button">Tag 1</button></li>
  <!-- ... -->
</ul>

Then the javascript:

$('#tagList li button.tag-button').click((e) => {
  const thisButton = $(e.target).hasClass('tag-button')
    ? $(e.target) : $(e.target).closest('.tag-button');
  // do something with thisButton
});

This ensures that you are targeting the element that the click was registered on. If you have any nested markup inside your button (such as or ) then it is possible for the event target to be the nested element rather than the element you wanted to assign the click to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top