Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

61
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!