0

I am trying to hide an HTML div with Javascript and am getting an error

JavaScript runtime error: Unable to get property 'style' of undefined or null reference

Here is my JavaScript code:

if (typeof(jsondata[0]) == 'undefined') {
    alert('should be hidden');
    document.getElementById("unassignedDevices").style.visibility = "hidden";
}

and here is my HTML:

<div id="unassignedDevices">
    <button id="unassignedDevicesbutton" class="button-basicmenu" onclick="findUnassignedDevices();">Find unassigned Devices</button>

    <table id="gridunassignedDevices"></table>

</div>

So when I start debugging, the page alerts 'should be hidden' and then I get the JavaScript runtime error.

How can I hide this div?

Mark
  • 2,354
  • 11
  • 27
  • 48
Ryan Weaver
  • 382
  • 11
  • 20
  • 2
    possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Teemu May 12 '15 at 16:45
  • on what event does the `if()` execute? – Shaunak D May 12 '15 at 16:46
  • set breakpoint where the alert is and check if your div exists in the dom or something has removed it – Pavel Kolev May 12 '15 at 16:51

2 Answers2

3
$(document).ready(function(){
   if (typeof (jsondata[0]) == 'undefined') {
      $('#unassignedDevices').hide();
    }
});
Ted
  • 13,992
  • 2
  • 31
  • 54
1

Javascript is faster than jQuery a little bit, but why cant you used jQuery instead of pure javascript alone ?

hir is sample code for the hide option. sample 1:

 $(document).ready(function(){
         $('#id').hide();
     });

sample 2:

$(function(){
   var index = {
      init: function(){
        //all jQuery calls
        $(document).on('click', '#id', this.exe_this_func);
      },
      exe_this_func: function(e){
          $(this).hide();
          e.preventDefault();
      }
   }
   index.init();
})();