views:

13

answers:

2

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

A: 

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 === 1 );  

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

patrick dw
The nodeValue could be blank/empty/null, no? `!!(document.createElement('p')).nodeValue`
meder
@meder - It was a mistype.
patrick dw
A: 

A node? A DOM element? it would have a .nodeType property.

Regarding nodeValue for the other answer, the nodeValue can be empty but a node will always have a nodeType.

meder