trying to change inner html of h1 tag but js throwing an error

Viewed 378
   the javascript below is the line 13 and the h1 is my html tag 

index.js:13 Uncaught TypeError: Cannot set property 'innerHTML' of null at index.js:13

<h1 id="text">javascript practice</h1>

document.getElementById('text').innerHTML = 'hey there';
2 Answers

you have to sure, the Element mounted in DOM

you can use like this

window.addEventListener('DOMContentLoaded', (event) => {
     document.getElementById('text').innerHTML = 'hey there';
});

In this snippet , your code run when all of the nodes (elements) loaded

Maybe add a function for the JavaScript? That would fix the issue. A great example would be:

const h1 = document.getElementById('text');

h1.addEventListener('click', () => {
h1.innerHTML = <p>Hey There</p>
})
Related