How to set $(this) as the clicked element

918 views javascript
0

In the following code:

// submit an item
$(document).on("click", ".match-item", function(event) {


    // how to set $(this) == $('.match-item') clicked?

});

I'm looking to retrieve $(this) as the clicked item and not the document itself. How would I do this?

answered question

this appears to indeed refer to the clicked element? jsfiddle.net/eqh36m0r

Why do you want to use $(this) instead of $(event.target)? You can't change the value of this inside the function.

as per jquery documentation api.jquery.com/delegate this actually is clicked element, why don't you just use it instead of set?

2 Answers

12

This is more of clarification rather than answer.

this is already referring to the currently clicked element.

$(document).on("click", ".match-item", function(event) {
  console.log($(this).attr('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  Parent
  <div class="match-item">----Click Me</div>
</div>

posted this
9

How about

$('.match-item').click(function() {
     //your code with $(this) here
});

I am pretty sure $(this) will refer to the element with class match-item

posted this

Have an answer?

JD

Please login first before posting an answer.