jquery: test whether input variable is dom element

前端 未结 4 1904
清歌不尽
清歌不尽 2021-01-02 03:50

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 i         


        
相关标签:
4条回答
  • 2021-01-02 03:51

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

    var myID = $(myInput).attr('id') ? $(myInput).attr('id') : myInput;
    
    0 讨论(0)
  • 2021-01-02 04:02

    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.

    0 讨论(0)
  • 2021-01-02 04:11

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

    0 讨论(0)
  • 2021-01-02 04:16

    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

    0 讨论(0)
提交回复
热议问题