Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an element is a drop down list element or a text input element, given its id?

In Javascript, given the id of an element (in a String format), how can I check if the id of the element refers to a drop down list element, or a text input element?

The function should return true if the id refers to a drop down list (<select>) element, or a text input element, and false otherwise.

like image 519
omega Avatar asked Sep 07 '25 13:09

omega


1 Answers

Try using: document.getElementById('idNameGoesHere').tagName

So the function could be:

function isSelectOrTextField(idName) {
    var element = document.getElementById(idName);
    if(element.tagName === 'SELECT') {return true;}
    if(element.tagName === 'INPUT' && element.type === 'text') {return true;}
    return false;
}

You could expand this to check for <textarea> as well.

EDIT : Or choose jbabey's answer as it's using nodeName and is better formatted.

apparently nodeName has wider browser support.

like image 151
jfrej Avatar answered Sep 09 '25 04:09

jfrej