Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda