Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading