¿Cómo dirijo el message usando JavaScript aquí para escribir en la etiqueta? Aquí está mi código HTML:
<h1 message = "this is the title of the page"></h1> El message solo debe mostrarse en determinadas circunstancias. Solo me preguntaba cómo usaría JavaScript para tomar ese elemento e inyectar su contenido en la etiqueta h1 cuando sea necesario.
Podrías hacerlo como se muestra a continuación. Siéntase libre de adaptarlo a su caso de uso, ya que por ahora, se escribirá en <h1> tan pronto como se cargue y se ejecute el script.
const h1 = document.querySelector("h1"); h1.textContent = h1.getAttribute("message"); <h1 message = "this is the title of the page"></h1>El método getAttribute se utiliza para get el valor de cualquier atributo en la etiqueta html.
Sintaxis de usar getAttribute
element.getAttribute (attributename);
const target = document.querySelector("h1"); // Original attribute console.log(target.getAttribute("message")) <h1 message="I am message in h1 tag"></h1> El método setAttribute se utiliza para set el valor de cualquier atributo en la etiqueta html.
Sintaxis de usar setAttribute
element.setAttribute(attributename, attributevalue);
const target = document.querySelector("h1"); // Original attribute console.log(target.getAttribute("message")) // changed attribute target.setAttribute("message","message attribute changed") console.log(target.getAttribute("message")) <h1 message = "this is the title of the page"></h1>https://stackoverflow.com/questions/72569107/use-javascript-to-write-text-into-html-interface#