检查DOM Element是否为复选框

Nip*_*una 18 javascript jquery dom

如何检查给定的DOM元素是否为复选框.

场景:

我有一组文本框和复选框,其中的值是动态分配的.我没有办法确定DOM元素是复选框还是文本框.

fca*_*ran 53

只使用vanilla javascript即可

if (el.type && el.type === 'checkbox') {
   ...
}
Run Code Online (Sandbox Code Playgroud)

甚至更短

if ((el || {}).type === 'checkbox') {
   ...
}
Run Code Online (Sandbox Code Playgroud)

或者在现代浏览器中你可以使用 matches()

if (el.matches('[type="checkbox"]') {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 许多年后....你可能想要'toLowerCase`那个类型值,不是吗? (2认同)

Sal*_*n A 15

如果你正在使用jQuery,你可以使用:checkbox伪类选择器和is方法:

if($("#that-particular-input").is(":checkbox")) {
}
Run Code Online (Sandbox Code Playgroud)


Leo*_*nid 11

检查一切

function isCheckbox (element) {
   return element instanceof HTMLInputElement 
      && element.getAttribute('type') == 'checkbox'
}
Run Code Online (Sandbox Code Playgroud)


jbr*_*rnd 5

if( $(element)[0].type == "checkbox" ) {

}
Run Code Online (Sandbox Code Playgroud)

或者

if( $(element).is(':checkbox') ) {

}
Run Code Online (Sandbox Code Playgroud)