Webnet Webnet - 1 year ago 110
Javascript Question

Check if variable is a valid node element

How can I change a JS element to see if it is a node or an empty variable?

Answer Source

It depends on what you mean by an empty variable.

If you mean it hasn't had a value assigned, you can check for undefined

alert( someVariable !== "undefined" );

Or if you know it has a value, and need to see if it is an element, you could do something like this:

alert( someVariable && someVariable.nodeType );  

Or if you need to verify that it is a type 1 element, you could do this:

alert( someVariable && someVariable.nodeType === Node.ELEMENT_NODE );  

This eliminates text nodes, attribute nodes, comments, and a bunch of others.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download