Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
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
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!