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); }
Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.
Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} . The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With