Tengo un archivo html (convertido de docx) y no tiene nombres de clase ni identificadores. ¿Cómo puedo diseñarlo usando JS? Por ejemplo, si necesito cambiar el color del encabezado del siguiente archivo HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="./script.js"></script> <title>Document</title> </head> <body> <h1>This is the heading</h1> <p>Hello, my name is xyz and this is a para</p> </body> </html> Esto es lo que probé, pero document.getElementByTagName() no devuelve el elemento como document.getElementById()
console.log('hello world'); Heading = document.getElementsByTagName('h1'); console.log(Heading); Heading.style.color = 'blue';Editar: probé el siguiente código, pero devuelve indefinido
console.log('hello world'); Heading = document.getElementsByTagName('h1')[0]; console.log(Heading); Heading.style.color = 'blue';También puede probar document.querySelector() .
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h1>This is the heading</h1> <p>Hello, my name is xyz and this is a para</p> </body> <script type="text/javascript"> const header = document.querySelector('h1'); console.log(header); header.style.color = 'blue'; </script> </html>Otra cosa a tener en cuenta es que debemos esperar a que se cargue la página; de lo contrario, su código javascript se ejecuta primero y regresa indefinido.
Puede asegurarse de que javascript se ejecute después de cargar la página utilizando cualquiera de las siguientes formas:
document.addEventListener("load", FUNCTION);<body onload="FUNCTION()"><script src="SCRIPT.js" defer>El problema en su código es que getElementsByTagName devuelve una matriz, pero está usando como si fuera un solo elemento.
Prueba esto:
window.addEventListener('load', () => { const heading = document.querySelector('h1'); heading.style.color = 'blue'; }); <h1>This is the heading</h1> <p>Hello, my name is xyz and this is a para</p>Actualice su código de esta manera. importaste el script antes de html. Hay dos soluciones. primero debe importar el script después de html o usar
window.addEventListener window.addEventListener('load', () => { const heading = document.querySelector('h1'); heading.style.color = 'blue'; }); <h1>This is the heading</h1> <p>Hello, my name is xyz and this is a para</p>