Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an element is a form field

Tags:

jquery

dom

Any convenient ways to determine if a selected element is a form field, i.e is an input, select, checkbox etc?

like image 245
Mark Nguyen Avatar asked Jul 27 '12 13:07

Mark Nguyen


2 Answers

In pure JavaScript you could do something like the Sizzle Engine

/^(?:input|select|textarea|button)$/i.test(el.nodeName)

Example

/**
 * Test is form action element
 * @param {Object} el 
 * @return {Boolean} true if a form action element
 */
const isInput = el => /^(?:input|select|textarea|button)$/i.test(el.nodeName);


// DEMO:
document.querySelectorAll('.foo').forEach(el => console.log(isInput(el)));
<textarea class="foo">test</textarea>
<button class="foo">test</button>
<input class="foo" type="text">
<div class="foo">test</div>
<p class="foo">test</p>

https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139

like image 154
Roko C. Buljan Avatar answered Sep 21 '22 23:09

Roko C. Buljan


Use plain javascript:

$("#someelement")[0].tagName // will return name of tag (div, p, input, select, etc...)

The first index [0] of any jQuery object will return its DOM object. To do it completely in javascript:

document.getElementById("someelement").tagName;
like image 23
Austin Avatar answered Sep 19 '22 23:09

Austin