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>
p:last-of-type works well for this:
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>
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>
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>