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

315
Visualizações
JavaScript: Not able to get tagName on click

I want to get tagName of any element inside the iframe onclick. However, I'm not being able to do that. I'm new to JavaScript. Where am I wrong?

<div class="flex-child green">
    <p id="a">You clicked on: </p>
    <iframe
      id="zzz"
      srcdoc="<html><h1>hello</h1><button>click me!</button></html>"
      width="500"
      height="500"
      onload="clickfn()"
    ></iframe>
  </div>
</div>

<script>
  function clickfn() {
    x = document.getElementById("zzz").target.tagName;
    document.getElementById("a").innerHTML = x;
  }
</script>

<style>
  .flex-container {
    display: flex;
  }

  .flex-child.green {
    flex: 1;
  }
</style>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For the shown code (using srcdoc) you should be able to attach the event listener to the contentWindow of the iframe:

document.getElementById("zzz").addEventListener('load', iframeLoaded)

function iframeLoaded() {
  document.getElementById("zzz").contentWindow.addEventListener('click', function(e) {
    document.getElementById("a").innerHTML = e.target.tagName;
  })
}
.flex-container {
  display: flex;
}

.flex-child.green {
  flex: 1;
}
<div class="flex-child green">
  <p id="a">You clicked on: </p>
  <iframe id="zzz" srcdoc="<html><h1>hello</h1><button>click me!</button></html>" width="500" height="500"></iframe>
</div>

Whether this works or not depends on the security headers send by the server, here on StackOverflow it does not work. On jsfiddle.net it works.

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