javascript - Solving Cannot read property 'innerHTML' of null using .on()? -


i've gotten error:

cannot read property 'innerhtml' of null

and i've been having @ other answers on stackoverflow , lot of them solve using $(document).ready , although fixes issue it's not efficient in case time page takes load dom can slow on occasion (+7 seconds) , rather id available, can use it.

is there way me this? i've been looking .on() try see if id exists not sure if can used way way i'm using means method never used.

the javascript file in included in head id in jsp further down.

using $(document).ready:

$(document).ready(function() {         updatecontainercount();         function updatecontainercount() {             var countelement = document.getelementbyid("countelement");             if (count > 0) {                 countelement.innerhtml += ' (' + count + ')';             }         } }); 

using .on() like:

$('#countelement').on("load", function() {         updatecontainercount();         function updatecontainercount() {             var countelement = document.getelementbyid("countelement");             if (count > 0) {                 countelement.innerhtml += ' (' + count + ')';             }         } }); 

you can directly manipulate dom element long sure has been loaded.

for example, can put part of code right after html declaration:

<div id="countelement"></div> <script>     var countelement = document.getelementbyid("countelement");     if (count > 0) {         countelement.innerhtml += ' (' + count + ')';     } </script>   

i pretty sure not considered practice, use approach in projects - in places really important execute script right after element dom loading, without waiting document loaded.

p.s. looks can set html on back-end. if yes, better generate server-side.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -