Este script cambiará el segundo párrafo a "¡Hola mundo!"
Pero si agrego un tercer párrafo, ¿cómo haría que cambiara automáticamente el tercer párrafo?
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 funciona bien para esto:
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>Solo necesita cambiar el código de bits para obtener la etiqueta del último párrafo
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>Tu guión no cambiará el segundo párrafo sino el tercero. Puede almacenar todos los párrafos en una matriz y simplemente elegir el último así:
<!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>