0

My code is currently returning null when trying to access an element in HTML. Strange thing is that it is working perfectly fine when testing in JSFiddle. Here is the copy of the jsfiddle link: http://jsfiddle.net/6f77q/115/.

This is what I have done in two separate files on my computer:

index.html

<script src="some.js"></script>
<select id="theid" name = "navyOp" onchange="test(this);"> 
<option selected = "selected">Select a Navy Op Area</option>
<option value = "AN01">AN01</option>
<option value = "AN02">AN02</option>
<option value = "AN03">AN03</option>
</select>

some.js

var earrings = document.getElementById('theid');
var anode=document.createElement("option");
anode.text="hello";
earrings.add(anode);
window.test = function(e){
        alert(e.value);

}

I'm really confused as to why anode is returning null. Any ideas why this may be happening where it's working in JSFiddle but not locally?

Thanks!

trynacode
  • 361
  • 1
  • 8
  • 18
  • 5
    The scripts you write in jsfiddle are by default executed in an `onload` callback. But you placed your script right before the html code containing `theid` so at the time when your `document.getElementById('theid');` is executed, the html containing `theid`was not parsed and the element `theid` is not in the DOM. – t.niese Sep 15 '16 at 05:24
  • @t.niese – Your comment is more descriptive _than_ answer :P – Rayon Sep 15 '16 at 05:28
  • I had a feeling that was the issue so what I had done was copied that – trynacode Sep 15 '16 at 05:33
  • A script element at the end of the body (just before `

    `) and no onload callback is my preference - note that onload doesn't just wait for all elements to be parsed, it also waits for images to download, etc. If you do want to use a load-style handler, use jQuery's `$(document).ready(...)` (or vanilla JS's DOMContentLoaded).

    – nnnnnn Sep 15 '16 at 05:36
  • Oh alright that's definitely easier to do. Silly mistake, thanks for the quick help guys! – trynacode Sep 15 '16 at 05:39

1 Answers1

2

Wrap your code in a domready/onload event,your code tries to execute but the elements are not yet present on the page so the script doesn't do what you want, the domready/onload event allows you to execute the code after all elements have been properly added to the page

madalinivascu
  • 32,064
  • 4
  • 39
  • 55