开发者

jquery: test whether input variable is dom element

I would like to write a jquery function that accepts either a dom element or its id as input:

function myfunction(myinput){
 // pseudocode:
 // if (myinput is dom element){
 //   var myID开发者_如何学JAVA = $(myinput).attr('id');
 // } else {
 //   var myID = myinput;
 // }

 // Do stuff with myID ...

}

Question: How can I tell whether myinput is a dom element???


It's easier to do the check the other way around - check if it's a string if so use it to get an ID else treat it as a DOM node/element and handle it as if it was one.

function myfunction(myinput) {

    var myId;

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

    // do something

}

or if you really want to check against if it's HTMLElement then every DOM html element extends HTMLElement abstract interface. Check MDC for more info on HTMLElement.

    ...

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

    ...

In the end it won't really matter... your call!

Tom


You would implement your function like this:

function myfunction(myinput){

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

 // Do stuff with myID ...

}

More information about nodeType.


I wonder if a nice ternary would work, something like this

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜