0

I'm having a problem with the getElementById in javascript, the console just says 'cannot read property 'style' of null, i.e the element is null, even though it is not null?

html

<h1 id="title">Title</h1>

javascript

document.getElementById('title').style.color = 'red';
marina
  • 1
  • Can't reproduce. – lilezek Aug 30 '17 at 13:24
  • I think you are trying to access before DOM gets loaded. –  Aug 30 '17 at 13:24
  • how do i execute the code after the dom gets loaded? – marina Aug 30 '17 at 13:28
  • Read this : https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Ofisora Aug 30 '17 at 13:29
  • If element is dynamic, browser does that sometimes. SO, we have to apply operation on element on body load or document load. –  Aug 30 '17 at 13:30
  • Duplicate of https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element –  Aug 30 '17 at 13:31
  • 2
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – HaveSpacesuit Aug 30 '17 at 13:37
  • thank you slacker, i've moved my script to the bottom of the html document, and by the looks of things it seems to have worked! thank you for your help – marina Aug 30 '17 at 14:15

2 Answers2

0

document.getElementById('title').style.color = 'red';
<h1 id="title">Title</h1>

See it's working..

  • Annoyingly it's not working for me on brackets, I am using chrome to run the code and it's not working. Do you have any other suggestions? – marina Aug 30 '17 at 13:26
  • check the length of that element first. if it's 0 OR 1 and keep the JS inside document.load –  Aug 30 '17 at 13:28
0

are you tying to set the color of the h1 before the dom is loaded? try this:

<body onload="myFunction()">

function myFunction(){
     document.getElementById('title').style.color = 'red';
}
schylake
  • 434
  • 3
  • 14