How to find element type in JQuery

前端 未结 2 1666
逝去的感伤
逝去的感伤 2021-01-29 02:19

I have an array with different elements inside it. Like array contain input elements and select elements. I want to check for particular type. I tried this but it didn\'t work

相关标签:
2条回答
  • 2021-01-29 03:02

    You can use either the .tagName property (which always returns uppercase for HTML):

    $('.mandotary').each(function(index, element) {
        if (element.tagName == "INPUT") {
            // code here
        } else if (element.tagName == "SELECT") {
            // code here
        }
    });
    

    Or, you can use jQuery's .is():

    $('.mandotary').each(function(index, element) {
        var $element = $(element);
        if ($element.is('input')) {
            // code here
        } else if ($element.is('select')) {
            // code here
        }
    });
    

    Even better would probably be to let the selector do all the work for you and just select the items you want for a particular operation and operate on the desired selector like this:

    $('input.mandotary').hide();
    $('select.mandotary').show();
    
    0 讨论(0)
  • 2021-01-29 03:21

    Just use .is() to match the tag name:

    if (element.is('input'))
    

    But ideally rework the code and don't check for tag names in your loop.

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