-1

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I made a snippet. It changed the THIRD paragraph since JS arrays and collections stat at 0. Updated to do what you said it does – mplungjan Dec 03 '21 at 14:46
  • 3
    https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName tells you that getElementsByTagName returns an HTMLCollection, and if you follow the link to that, you'll see that it has a `length` property. – CBroe Dec 03 '21 at 14:46

3 Answers3

1

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>
Rob Moll
  • 3,345
  • 2
  • 9
  • 15
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>
Behemoth
  • 5,389
  • 4
  • 16
  • 40
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>
Jatinder
  • 96
  • 2
  • 11