document.getElementById('div') returns null

in Script development
Subscribe to document.getElementById('div') returns null 3 posts, 3 voices



William Scriptwright

I'm trying to do this script but it doesn't seem to find any properties for any element that is located on a webpage.

var elmNewContent = document.createElement('a'); elmNewContent.href = 'http://example.com/'; elmNewContent.appendChild(document.createTextNode('click here')); var elmFoo = document.getElementById('div'); elmFoo.parentNode.insertBefore(elmNewContent, elmFoo);
TypeError on line 5: elmFoo has no properties

 
oldguy Scriptwright

You only can get an element with the id 'div' if there is one... I guess you mean document.getElementsByTagName('div'). Then you'll get a list of all available elements of type 'div' and can iterate it to find the one you're searching for.

 
Joel H Scriptwright

You can also do this as a quick test for whether or not anything was returned:
alert(document.getElementsByTagName('div'));

null means nothing was returned, Object Collection means you did get something.

-Joel