Get selected element type

JavascriptJquery

Javascript Problem Overview


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>

Javascript:

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);
}

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSilver LightView Question on Stackoverflow
Solution 1 - JavascriptJacob RelkinView Answer on Stackoverflow
Solution 2 - JavascriptlonesomedayView Answer on Stackoverflow