-2

If I have the following html structure:

<div class ='wrapper'></div>

<div class ='wrapper'></div> I want to get this element

<div class ='wrapper'></div>

I tried doing something like this:

$(document).on('click', 'wrapper', ()=>{
  var element = $(this); //not sure how to do this 
});

How can I get a reference to the clicked element so I can used it for things like $(element).siblings() and next(), etc.

The method that I tried to use, selects all the elements with that class, i want to get only the element clicked on, Is there a way I can do that ?

Marcel
  • 73
  • 3
  • Read this regarding e.target and e.currentTarget https://stackoverflow.com/q/12077859/8252164 – samuellawrentz Jul 27 '18 at 07:36
  • afaik, `this` should refer to the clicked element in JQuery. But if you use an arrow function, it might not work since arrow functions have special rules for `this`. `event.target` is a nice non-jquery way of getting the reference if you need the `this` context to not refer to the element. – Shilly Jul 27 '18 at 07:37
  • 2
    First add a dot: `$(document).on('click', '.wrapper',` – mplungjan Jul 27 '18 at 07:40
  • 1
    Nice catch!! @mplungjan – samuellawrentz Jul 27 '18 at 07:46

2 Answers2

0

$(document).ready(function() {

  $(".wrapper").click(function() {
    var clickedElement = $(this);
    alert(clickedElement.text());
    console.log(clickedElement.siblings());
    console.log(clickedElement.next());
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='wrapper'>Click here One</div>
<div class='wrapper'>Click here Two</div>
<div class='wrapper'>Click here Three</div>
Prachi
  • 3,022
  • 11
  • 31
-1

This is correct:

$(document).on('click', '.wrapper', function() {
  var element = $(this); //not sure how to do this 
});

but when you are referencing you should by

element.siblings()

and not by

$(element).siblings()
Sonia
  • 1,769
  • 1
  • 10
  • 13