Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
How do I copy text from an <Input> by using getElementbyTagName?

I am trying to create a button that doesn't use ID to copy text from an input text field.

I thought the best way to do this would be using an event listener and then on click activate the function that would copy text from the input value.

HTML:

<div>
 <input type="text" value="copy this" readonly>
 <button type=button id='btn'>Copy URL</button>
</div>

JS:

  <script> 
  document.querySelect('#btn').addEventListener('click', function() {
   jimsFunction();
});
  
  function jimsFunction() {
  var copyText = document.getElementByTagName('input').value;
  copyText.select();
  copyText.setSelectionRange(0, 99999); 
  navigator.clipboard.writeText(copyText.value);
  alert("Copied: " + copyText.value);
  }    

</script>

Can someone point out what I'm doing wrong here?

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. First getting by tag is elements . You were missed s
document.getElementByTagName ->document.getElemenstByTagName

  1. Loop elements and add event

Try it :

document.getElementById('btn').addEventListener('click', function() {
   jimsFunction(this)
});
let btns = document.getElementsByClassName('btn')
Array.from(btns).forEach(ele => {
  ele.addEventListener('click', function() {
   jimsFunction(this)
  });
})  
function jimsFunction(input) {
  let ele = input.previousElementSibling
  ele.select()
  ele.setSelectionRange(0, 99999)
  navigator.clipboard.writeText(ele.value)
  alert("Copied: " + ele.value)
}
<div>
 <input type="text" value="copy this" readonly>
 <button type=button id='btn'>Copy URL</button>
</div>
<div>
 <input type="text" value="text 1" readonly>
 <button type=button class='btn'>Copy URL</button>
</div>

<div>
 <input type="text" value="text 2 (different)" readonly>
 <button type=button class='btn'>Copy URL</button>
</div>

You are duplicate id, you should change to class

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda