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???

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

HTMLElement wasn't working for me in some browser (probably IE8) so now I'm checking for nodeType
You could do $(myinput).length > 0 to see if element exists in the DOM.
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.

1 Comment

+1 for this solution. jQuery code uses this in its isPlainObject function to exclude DOM nodes.
0

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

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

Comments

-2

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

2 Comments

Nope, there's no such class as domElement.
What you mean is Element or Node ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.