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

62
Vistas
Encuentra el último índice de getElementsByTagName

Este script cambiará el segundo párrafo a "¡Hola mundo!"

Pero si agrego un tercer párrafo, ¿cómo haría que cambiara automáticamente el tercer párrafo?

 function myFunction() { document.getElementsByTagName("p")[1].innerHTML = "Hello World!"; }
 <p>Click the button to change the text of this paragraph.</p> <p>This is also a paragraph.</p> <p>This is also a paragraph.</p> <button onclick="myFunction()">Try it</button>

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

0

p:last-of-type funciona bien para esto:

:último-de-tipo

 function myFunction() { document.querySelector("p:last-of-type").innerHTML = "Hello World!"; }
 <p>Click the button to change the text of this paragraph.</p> <p>This is also a paragraph.</p> <p>This is also a paragraph.</p> <button onclick="myFunction()">Try it</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Solo necesita cambiar el código de bits para obtener la etiqueta del último párrafo

 function myFunction() { //it will return the array of paragraph tags let pTags = document.getElementsByTagName("p"); //to get last paragraph simple minus one the length of array pTags[pTags.length - 1].innerHTML = "Hello World!"; }
 <p>Click the button to change the text of this paragraph.</p> <p>This is also a paragraph.</p> <p>This is also a paragraph.</p> <p>This is also a paragraph.</p> <button onclick="myFunction()">Try it</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Tu guión no cambiará el segundo párrafo sino el tercero. Puede almacenar todos los párrafos en una matriz y simplemente elegir el último así:

 <!DOCTYPE html> <html> <body> <p>Click the button to change the text of this paragraph.</p> <p>This is also a paragraph.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { const ps = document.getElementsByTagName("p"); ps[ps.length -1].innerHTML = "Hello World!"; } </script> </body> </html>

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