11

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 = $(myinput).attr('id');
 // } else {
 //   var myID = myinput;
 // }

 // Do stuff with myID ...

}

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

moondog
  • 1,537
  • 5
  • 22
  • 34
  • This has already been asked: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object – Shane Garelja Feb 17 '11 at 20:37

4 Answers4

21

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

Tom Tu
  • 9,573
  • 35
  • 37
6

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.

Adam Prax
  • 6,413
  • 3
  • 30
  • 31
  • +1 for this solution. jQuery code uses this in its isPlainObject function to exclude DOM nodes. – sma Jul 12 '13 at 18:30
0

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

var myID = $(myInput).attr('id') ? $(myInput).attr('id') : myInput;
Ilia Draznin
  • 1,026
  • 2
  • 12
  • 24
-2

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

devzorg
  • 105
  • 7