开发者

Get selected element type

开发者 https://www.devze.com 2023-02-05 03:32 出处:网络
I want to get the type of element, that I\'ve got selected using jQuery selectors. Markup: <select name=\"a\"></select>

I want to get the type of element, that I've got selected using jQuery selectors.

Markup:

<select name="a"></select>
<input name="b" type="text" />
<textarea name="c"></textarea>

J开发者_开发技巧avascript:

var field_names = new Array(
    'a',
    'b',
    'c'
);

for(var i = 0; i < field_names.length; i++) {
    var field = $('[name=' + required_fields[i] + ']:visible');

    // ?????
    // What do I write here to get one of those outputs:
    //    Element with name a is <select>
    //    Element with name b is <input>
    //    Element with name c is <textarea>

    alert('Element with name ' + required_fields[i] + ' is ' + element_type);
}


Use the DOM element's tagName property:

var element_type = field[0].tagName;

Note that browsers are not entirely consistent about the case returned by tagName, so you should probably call toLowerCase to be safe: field[0].tagName.toLowerCase().


Simple:

var element_type = '<' + field.get(0).tagName.toLowerCase() + '>';

In a nutshell, this retrieves the DOM element associated with field and gets its tag name via the tagName attribute inherited from DOMElement, then transforms the result to lowercase using String's toLowerCase() method. Some browsers will return the tagName in uppercase, so for consistency you should transform it to lower case.

0

精彩评论

暂无评论...
验证码 换一张
取 消