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

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

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

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

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