2010-09-23 26 views

Respuesta

17

Depende de lo que signifique una variable vacía.

Si usted quiere decir que no ha tenido un valor asignado, se puede comprobar si hay undefined

alert(someVariable !== "undefined"); 

O si usted sabe que tiene un valor, y necesita ver si se trata de un elemento, que podría hacer algo como esto:

alert(someVariable && someVariable.nodeType); 

O si es necesario verificar que se trata de un elemento de tipo 1, usted puede hacer esto:

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

Esto elimina los nodos de texto, los nodos de atributo, los comentarios y a bunch of others.

+0

El nodeValue podría estar en blanco/vacío/null, que no? '!! (document.createElement ('p')). nodeValue' –

+0

Siempre que no sea otro objeto con la propiedad' nodeType'. Sin embargo, las posibilidades son escasas. – crush

5

¿Un nodo? Un elemento DOM? tendría una propiedad .nodeType.

En cuanto nodeValue para la otra respuesta, la nodeValue puede estar vacío, pero un nodo se siempre tener un nodeType.

5

usando el elemento HTML y echar un vistazo a la ficha Propiedades en Chrome Dev Herramientas podemos ver los descendientes:

html-> HTMLHtmlElement-> HTMLElement-> element-> Nodo-> EventTarget- > objeto

Ahora no queremos comprobar los 2 primeros no importa qué, demasiadas posibilidades diferentes para que nos dejan con HTMLElement o elemento. Entonces cuál es la diferencia?

HTML, HEAD, escritura, META, cuerpo, DIV, P y UL todos tienen la misma herencia:

HTMLElement-> element-> Nodo-> EventTarget-> Objeto

ahora unos resultados negativos de un típico documento donde:


<!DOCTYPE html>  DocumentType->Node->EventTarget->Object 
<!-- COMMENT --> Comment->CharacterData->Node->EventTarget->Object 

Por lo tanto, el nodo es el denominador común, pero la pregunta es cómo buscar un nodo de DOM válido, es cómo verificar si hay un elemento de nodo DOM válido. Por lo tanto, cualquier objeto con HTMLElement devolverá true; de ​​lo contrario, devolverá false.

Ok ahora usando las herramientas de Chrome Dev deja mirada en el elemento HTML:

$obj.nodeType;  //1  No help what so ever 
$obj.nodeName;  //HTML Gives use the tag names 
$obj.nodeValue;  //null Waste of DOM space 

vamos a ver el prototipo o __proto?

$obj.prototype.nodeType; //TypeError 
$obj.prototype.nodeName; //TypeError 
$obj.prototype.nodeValue; //TypeError 

$obj.__proto__.nodeType; //undefined 
$obj.__proto__.nodeName; //undefined 
$obj.__proto__.nodeValue; //undefined 

Ok, así que usar el nodo está muerto para usar. Vamos a movernos al constructor.

$obj.constructor.name  
//"HTMLHtmlElement"  promising... 

$obj.constructor.__proto__.prototype.toString() 
//[object Object] 

$obj.constructor.__proto__.constructor.name 
Function 

$obj.constructor.__proto__.prototype.constructor.name 
HTMLElement 
//BINGO 

Ahora vamos a envolver en una función de utilidad limpia y eficiente.

//readable version 
isElement=function($obj){ 
    try { 
     return ($obj.constructor.__proto__.prototype.constructor.name)?true:false; 
    }catch(e){ 
     return false; 
    } 
} 

/** 
    * PRODUCTION 
* Return true if object parameter is a DOM Element and false otherwise. 
* 
* @param {object} Object to test 
* @return {boolean} 
*/ 
isElement=function(a){try{return a.constructor.__proto__.prototype.constructor.name?!0:!1}catch(b){return!1}}; 

Pruebas:

$html=get('html')[0];   //[<html data-role=​"webpage" data-theme=​"dark" data-require=​"fa" data-hello=​"world">​…​</html>​] 
isElement($html);    //"HTMLElement" 
isElement($html.dataset);  //false 
isElement($html.firstChild); //"HTMLElement" 
isElement($html.textContent); //false 

$tail=gei('tail');    //<tail id=​"tail">​…​</tail>​ 
isElement($tail);    //"HTMLElement" 

isElement(get('title')[0]);  //"HTMLElement" 
+1

meder indica que siempre hay un nodeType y que es correcto. Eso fue lo primero que revisé y el valor es 1. El estándar define nodeType 1 como "Elemento \t Representa un elemento \t Elemento, Texto, Comentario, ProcessingInstruction, CDATASection, EntityReference". La pregunta era para 'Elemento', no para Texto, Comentario, etc. ¿Entonces mi función isElement() es la correcta? o estoy equivocado? – NlaakALD

Cuestiones relacionadas