Andrew Bro
Andrew Bro

Reputation: 491

how to get an HTML element who called a function?

I have HTML elements with 'onclick' attribute like this one:

  <div class="item add pt-3" data-toggle="modal" data-target="#uploadModal" 
   onclick="myFunction();"><i class="ni ni-fat-add"></i></div>

Later in a script I want to have this element to manipulate it.

myFunction(){  
  $(theElement).data('target'); //example
}

Upvotes: 0

Views: 58

Answers (2)

DCR
DCR

Reputation: 15665

function myFunction(myEvent){  
 console.log( myEvent.getAttribute('data-toggle')) 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="item add pt-3" data-toggle="modal" data-target="#uploadModal" 
   onclick="myFunction(this);"><i class="ni ni-fat-add"></i>click me</div>

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47099

Just send it in:

onclick="myFunction(this);"

And then you get it as the first argument to your function:

function myFunction(theElement) {
  $(theElement).data('target');
}

But you should consider adding the event with JavaScript in the first place:

<div class="item add pt-3" data-toggle="modal" data-target="#uploadModal">...</div>

And your JavaScript file could contain something like:

// add click listeners to all DOM elements that have the class "add"
$('.add').on('click', function() {
  $(this).data('target');
});

Or without jQuery, and modern JavaScript:

document.querySelectorAll('.add').forEach(el => {
  el.addEventListener('click', () => {
    el.dataset.target;
  });
});

If the element is dynamically created, then you could consider using event delegation.

Upvotes: 1

Related Questions