0

var editor = {
  "test1": document.getElementById("a"),
  
  "test2": function() {
    return document.getElementById("a")
  },

  "editCont": function() {
    console.log(editor.test1.id); // this returns 'cannot read property 'id' of null'
    console.log(editor.test2().id); // when removing the above console.log, this returns 'a'
  }
}
<h1 id="a" onclick="editor.editCont()">Click me!</h1>

the console returns null for test1 and 'a' for the second.

Can editor.test1 work without having to put it in a function like editor.test2?

I understand that DOM element cannot be found if it doesn't exist however the second console.log works, whats the reason for the first console.log?

succeed
  • 650
  • 8
  • 20
  • Your example doesn't have an element with an id of `a`. Also, are you waiting for the DOM to load before running that code? – j08691 Dec 12 '14 at 16:20
  • Yes it can. However the element must exist at the moment you are trying to get a reference to it. – Felix Kling Dec 12 '14 at 16:20
  • @j08691 sorry, revised the code for simplification. Example now has an id of a' – succeed Dec 12 '14 at 16:27
  • @j08691 Given its on onclick event call isnt the DOM loaded already? – succeed Dec 12 '14 at 16:38
  • But you are creating `editor` and its properties *before* the DOM finished loading. – Felix Kling Dec 12 '14 at 16:39
  • @Leo by removing the 'console.log(editor.test1.id)' thus allowing the test2 to execute test2 does work. – succeed Dec 12 '14 at 16:40
  • @FelixKling however as they are being called from an onclick event are they not executed after the DOM loads? test2 works once you remove the 'console.log(editor.test1.id)' – succeed Dec 12 '14 at 16:46
  • Yes, `test2` is executed after the DOM is loaded. That means `return document.getElementById("a")` is executed after the DOM is loaded and hence it works. However, `test1` (and its value) is created before the DOM loaded. – Felix Kling Dec 12 '14 at 17:05

0 Answers0