[Javascript] Check if an element exists in the DOM
John Deighan
jdeighan at pcgus.com
Wed Oct 18 08:13:34 CDT 2006
At 08:49 AM 10/18/2006, you wrote:
>Hello.
>
>How do I check if an element with id="XYZ" is present in my page/DOM ?
>
>I've tried with:
>
>if ($('XYZ') == undefined) {
> // Do something
>} else {
> // Do something else
>}
>
>but, of course, javascript give me an error of undefined object.
The function named '$', I think, is part of a popular library named
prototype.js. You'd have to at a minimum be sure that it's loaded.
The standard DOM way would be:
if (document.getElementById('XYZ')===undef) {
Note that it's better to use '===' to compare to undef since '=='
will to type conversion on it's arguments so that,
e.g. 0==undef and ''==undef will return true, but the same
comparisons using '===' will return false.
More information about the Javascript
mailing list