Use JavaScript to write HTML element attribute text into HTML element

Issue

How do I target message using JavaScript here to write to the tag? Here is my HTML code:

<h1 message = "this is the title of the page"></h1>

The message should only show in certain circumstances. Just wondering how I would use JavaScript to grab that element and inject its contents into the h1 tag when needed?

Solution

You could do it as below. Feel free to adapt it to your use case, as for now, it will write into the <h1> as soon as the script is loaded and gets executed.

const h1 = document.querySelector("h1");
h1.textContent = h1.getAttribute("message");
<h1 message = "this is the title of the page"></h1>

Answered By – yousoumar

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.