Is there possibility to disable js when there is not code?
toplisek
3:02 pm on Jan 25, 2015 (gmt 0)
I have seen that sometimes it shows an error like: Error: TypeError: document.getElementById(...) is null Source File: sample.js application.
How to avoid this as it demands script when there is sample.js.
One simple way is to put javascript only on pages where is function but can be better way to put sample.js on all pages and working validation even there is not function?
Fotiman
3:46 pm on Jan 25, 2015 (gmt 0)
That means that your code in sample.js did something like this: document.getElementById('foo').someDomMethod(); And if 'foo' does not exist, it's trying to call a method on null, which will throw an error. To avoid this, change the code in sample.js to do something like this:
var foo = document.getElementById('foo'); if (foo) { foo.someDomMethod(); }
null is a falsy value, so when you do "if (foo)", that is basically checking to make sure an element was returned instead of null.
toplisek
8:54 am on Jan 26, 2015 (gmt 0)
I will give you real example and specific. there is installed simple tree menu javascript from URL: dynamicdrive.com
Error with line: var ultags=document.getElementById(treeid).getElementsByTagName("ul") Error: TypeError: document.getElementById(...) is null Source File: treemenu.js Line: 10
Javascript: ddtreemenu.createTree("myID", true);
Fotiman
12:43 pm on Jan 26, 2015 (gmt 0)
Yes, as I said, it's trying to call a method (getElementsByTagName) on null (the results of document.getElementById(treeid)).
Modify that script as follows:
var ultags, _treeid = document.getElementById(treeid); if (_treeid) { ultags = _treeid.getElementsByTagName("ul"); // code that uses ultags below }
toplisek
6:25 pm on Jan 26, 2015 (gmt 0)
Thank you. It works.
toplisek
12:15 pm on Feb 19, 2015 (gmt 0)
I'm testing better disable function.
Can be improved init function or this is mistake? jQuery(function() { treeMenus.init(); } );
treeMenus = { init: function() {
var ultags, foo = document.getElementById('foo'); if (foo) { ultags = foo.getElementsByTagName("ul"); ddtreemenu.createTree("foo", true); }