2011-02-17 20 views
11

Me gustaría escribir una función jQuery que acepta ya sea un elemento DOM o su identificación como entrada:jQuery: comprobar si la variable de entrada es elemento DOM

function myfunction(myinput){ 
// pseudocode: 
// if (myinput is dom element){ 
// var myID = $(myinput).attr('id'); 
// } else { 
// var myID = myinput; 
// } 

// Do stuff with myID ... 

} 

Pregunta: ¿Cómo puedo saber si myInput es un dom ¿¿¿elemento???

+0

Esto ya se ha preguntado: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you- check-if-a-javascript-object-is-a-dom-object –

Respuesta

20

Es más fácil hacer el cheque a la inversa - comprobar si es una cadena si a fin de utilizarlo para obtener un ID demás lo tratan como un nodo/elemento DOM y manejarlo como si fuera una .

function myfunction(myinput) { 

    var myId; 

    if (typeof myinput == 'string'){ 
     myId = myinput; 
    } else { 
     myId = myinput.id; // myinput.id is enough 
    } 

    // do something 

} 

o si realmente quiere comprobar si es contra HTMLElement entonces cada elemento HTML DOM se extiende interfaz abstracta HTMLElement. Check MDC para obtener más información sobre HTMLElement.

... 

    if (myinput instanceof HTMLElement){ 
     myId = myinput.id; // myinput.id is enough 
    } else { 
     myId = myinput; 
    } 

    ... 

Al final no importa ... ¡su llamada!

Tom

+0

¡Gracias! Esto es exactamente lo que necesitaba. – moondog

+2

HTMLElement no funcionaba para mí en algunos navegadores (probablemente IE8) así que ahora estoy buscando 'nodeType' –

+0

Puedes hacer' '' $ (myinput) .length> 0''' para ver si el elemento existe en el DOM. – designcise

-2

if(myinput instanceof domElement) alert("Yes");

+4

No, no existe una clase como 'domElement'. – BoltClock

+3

Lo que quiere decir es 'Elemento' o' Nodo';) – yckart

6

Usted podría poner en práctica su función como esta:

function myfunction(myinput){ 

if (myinput.nodeType){ 
    var myID = $(myinput).attr('id'); 
} else { 
    var myID = myinput; 
} 

// Do stuff with myID ... 

}

Más información sobre nodeType.

+0

+1 para esta solución. El código jQuery usa esto en su función isPlainObject para excluir nodos DOM. – sma

0

Me pregunto si un buen ternaria funcionaría, algo como esto

var myID = $(myInput).attr('id') ? $(myInput).attr('id') : myInput; 
Cuestiones relacionadas