javascript 如何在javascript中检查元素类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20494414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:37:24  来源:igfitidea点击:

How to check element type in javascript

javascriptjqueryhtmldom

提问by php_nub_qq

I have a situation in which i want to convert a <select>tag into a <input type="text">and <input type="text">into <select>bu using some condition. So how can i know that this element a type text or type select using id attribute.

我有我想要一个转换的情况<select>标记为<input type="text"><input type="text"><select>使用一些条件蒲式耳。那么我怎么知道这个元素是一个使用 id 属性的类型文本或类型选择。

采纳答案by Sunil Verma

By using

通过使用

$("#inputID").attr("type");

If you alert above you will get the type of input element, then you can apply checks accordingly.

如果您在上面发出警报,您将获得输入元素的类型,然后您可以相应地应用检查。

Ref here : http://api.jquery.com/attr/

参考这里:http: //api.jquery.com/attr/

UPDATE

更新

check using

检查使用

if(!$("#inputID").is("select")) {
    // the input field is not a select
}

got from a link while searching not tested though.

搜索时从链接中获取,但未经过测试。

回答by php_nub_qq

And also a pure javascript solution:

还有一个纯javascript解决方案:

function toggle(a){
    if(a.tagName === 'INPUT'){
        a.outerHTML = '<select id="toggle"></select>';
    }else{
        a.outerHTML = '<input type="text" id="toggle"/>'
    }
}

http://jsfiddle.net/M6qXZ/1/

http://jsfiddle.net/M6qXZ/1/

2018 ES6

2018 ES6

e => e.outerHTML = e.tagName === "INPUT" ? "<select id='toggle'></select>" : "<input id='toggle'/>"

回答by Blowsie

Get the element type using jQuery:

使用 jQuery 获取元素类型:

var elementType = $("#myid").prop('tagName');

var elementType = $("#myid").prop('tagName');

Get the input type attribute using jQuery:

使用 jQuery 获取输入类型属性:

var inputType = $("#myid").attr('type');

var inputType = $("#myid").attr('type');

回答by Sadako

the condicion could be for example:

例如,条件可以是:

   if($('#whateverid').attr('type') == "text")

回答by Arun P Johny

You can use .is()to test whether the elements is of type x like

您可以使用.is()来测试元素是否为 x 类型

Use :textselector to test for text input element

使用:text选择器测试文本输入元素

if($("#inputID").is(":text")){
    //to test for text type
}

Use element selectorto test for select element

使用元素选择器测试选择元素

if($("#inputID").is("select")){
    //to test for select
}