Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected element type

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); } 
like image 768
Silver Light Avatar asked Jan 18 '11 19:01

Silver Light


People also ask

How to check an elements type in js?

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.

How do you know if an element is selected?

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.


2 Answers

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.

like image 50
Jacob Relkin Avatar answered Oct 07 '22 03:10

Jacob Relkin


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

like image 29
lonesomeday Avatar answered Oct 07 '22 01:10

lonesomeday