-1

First of all, I know this kind of questions have been asked thousand of times, but why doesnt this work? I have a chrome extension with an options.html and a save button for saving things to local storage:

<div>       
    <button type="button" name="save" class="btn btn-primary btn-md active" id="save">SAVE</button>         
</div>      

And this is my options.js:

document.getElementById('save').addEventListener('click',
save_options);

However, it gives me this error in chrome console:

Uncaught TypeError: Cannot read property 'addEventListener' of null

What am I overlooking?

Noah
  • 471
  • 1
  • 6
  • 16
  • What comes first - script or button? – Banzay Mar 05 '17 at 14:38
  • Where / how are you including the JS? – SLaks Mar 05 '17 at 14:38
  • Thank you all, StasiekK answer worked. – Noah Mar 05 '17 at 15:19
  • The problem exists in portions of the JavaScript/HTML which you have not shown. Please provide a complete [mcve]. All answers are just *guessing* that the problem is a very common issue of trying to access an element before it exists. This question is about JavaScript/HTML/CSS, which is not unique to the Chrome extension environment. You should consider using a [snippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/). – Makyen Mar 05 '17 at 16:56
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer – Daniel Herr Mar 05 '17 at 18:24

2 Answers2

2

you are getting that error because you are trying to add an event listener to an element that has not been created yet, put your js script at the end of the body, or use the DOMContentLoaded event,

0

You try to add event listener to not yet created element. Add event istener to DOMContentLoaded to execute you'r listener after DOM is generated.

document.addEventListener("DOMContentLoaded", function() { 
  document.getElementById('save').addEventListener('click',
  save_options);
});

this should do the work.

StasiekK
  • 66
  • 1
  • 3