Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: test whether input variable is dom element

Tags:

jquery

dom

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

like image 611
moondog Avatar asked Feb 17 '11 20:02

moondog


People also ask

How do I know if a element is DOM?

To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.

How do you check if a JavaScript Object is a DOM object?

An Element object represents all HTML elements. Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator.

How do you check if an element is an input?

We can use the tagName property and type attribute of the DOM element to check if the DOM element is input or not. For the input DOM element, the tagName is INPUT .

How can check input value or not in jQuery?

Answer: Use the jQuery val() Method You can use the val() method to test or check if inputs are empty in jQuery.


2 Answers

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

like image 109
Tom Tu Avatar answered Oct 04 '22 17:10

Tom Tu


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.

like image 38
Adam Prax Avatar answered Oct 04 '22 16:10

Adam Prax