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

58
Vistas
Find the last index of getElementsByTagName

This script will change the second paragraph to "Hello World!"

But if I add a 3rd paragraph how would i have it automatically change the 3rd paragraph instead.

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 works well for this:

:last-of-type

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

Just need to change the little bit code to get last paragraph tag

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

Your script won't change the second paragraph but the third instead. You can store all paragraphs into an array and simply choose the last one like so:

<!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