Checking element type javascript

typeof

The typeof operator returns a string indicating the type of the operand’s value.

Try it

Syntax

Parameters

An expression representing the object or primitive whose type is to be returned.

Description

The following table summarizes the possible return values of typeof . For more information about types and primitives, see also the JavaScript data structure page.

Type Result
Undefined «undefined»
Null «object» (reason)
Boolean «boolean»
Number «number»
BigInt «bigint»
String «string»
Symbol «symbol»
Function (implements [[Call]] in ECMA-262 terms; classes are functions as well) «function»
Any other object «object»

This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed.

Examples

Basic usage

// Numbers typeof 37 === "number"; typeof 3.14 === "number"; typeof 42 === "number"; typeof Math.LN2 === "number"; typeof Infinity === "number"; typeof NaN === "number"; // Despite being "Not-A-Number" typeof Number("1") === "number"; // Number tries to parse things into numbers typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number typeof 42n === "bigint"; // Strings typeof "" === "string"; typeof "bla" === "string"; typeof `template literal` === "string"; typeof "1" === "string"; // note that a number within a string is still typeof string typeof typeof 1 === "string"; // typeof always returns a string typeof String(1) === "string"; // String converts anything into a string, safer than toString // Booleans typeof true === "boolean"; typeof false === "boolean"; typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean() // Symbols typeof Symbol() === "symbol"; typeof Symbol("foo") === "symbol"; typeof Symbol.iterator === "symbol"; // Undefined typeof undefined === "undefined"; typeof declaredButUndefinedVariable === "undefined"; typeof undeclaredVariable === "undefined"; // Objects typeof  a: 1 > === "object"; // use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof [1, 2, 4] === "object"; typeof new Date() === "object"; typeof /regex/ === "object"; // The following are confusing, dangerous, and wasteful. Avoid them. typeof new Boolean(true) === "object"; typeof new Number(1) === "object"; typeof new String("abc") === "object"; // Functions typeof function () > === "function"; typeof class C > === "function"; typeof Math.sin === "function"; 

typeof null

// This stands since the beginning of JavaScript typeof null === "object"; 

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0 . null was represented as the NULL pointer ( 0x00 in most platforms). Consequently, null had 0 as type tag, hence the typeof return value «object» . (reference)

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === «null» .

Using new operator

All constructor functions called with new will return non-primitives ( «object» or «function» ). Most return objects, with the notable exception being Function , which returns a function.

const str = new String("String"); const num = new Number(100); typeof str; // "object" typeof num; // "object" const func = new Function(); typeof func; // "function" 

Need for parentheses in syntax

The typeof operator has higher precedence than binary operators like addition ( + ). Therefore, parentheses are needed to evaluate the type of an addition result.

// Parentheses can be used for determining the data type of expressions. const someData = 99; typeof someData + " Wisen"; // "number Wisen" typeof (someData + " Wisen"); // "string" 

Interaction with undeclared and uninitialized variables

typeof is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, typeof will return «undefined» instead of throwing an error.

typeof undeclaredVariable; // "undefined" 

However, using typeof on lexical declarations ( let const , and class ) in the same block before the line of declaration will throw a ReferenceError . Block scoped variables are in a temporal dead zone from the start of the block until the initialization is processed, during which it will throw an error if accessed.

typeof newLetVariable; // ReferenceError typeof newConstVariable; // ReferenceError typeof newClass; // ReferenceError let newLetVariable; const newConstVariable = "hello"; class newClass > 

Exceptional behavior of document.all

All current browsers expose a non-standard host object document.all with type undefined .

typeof document.all === "undefined"; 

Although document.all is also falsy and loosely equal to undefined , it is not undefined . The case of document.all having type «undefined» is classified in the web standards as a «willful violation» of the original ECMAScript standard for web compatibility.

Custom method that gets a more specific type

typeof is very useful, but it’s not as versatile as might be required. For example, typeof [] is «object» , as well as typeof new Date() , typeof /abc/ , etc.

For greater specificity in checking types, here we present a custom type(value) function, which mostly mimics the behavior of typeof , but for non-primitives (i.e. objects and functions), it returns a more granular type name where possible.

function type(value)  if (value === null)  return "null"; > const baseType = typeof value; // Primitive types if (!["object", "function"].includes(baseType))  return baseType; > // Symbol.toStringTag often specifies the "display name" of the // object's class. It's used in Object.prototype.toString(). const tag = value[Symbol.toStringTag]; if (typeof tag === "string")  return tag; > // If it's a function whose source code starts with the "class" keyword if ( baseType === "function" && Function.prototype.toString.call(value).startsWith("class") )  return "class"; > // The name of the constructor; for example `Array`, `GeneratorFunction`, // `Number`, `String`, `Boolean` or `MyCustomClass` const className = value.constructor.name; if (typeof className === "string" && className !== "")  return className; > // At this point there's no robust way to get the type of value, // so we use the base implementation. return baseType; > 

For checking potentially non-existent variables that would otherwise throw a ReferenceError , use typeof nonExistentVar === «undefined» because this behavior cannot be mimicked with custom code.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

How to check element type in javascript

Solution 3: You can use .is() to test whether the elements is of type x like Use :text selector to test for text input element Use element selector to test for select element Solution 4: Get the element type using jQuery: Get the input type attribute using jQuery: Question: I am trying to determine if the selected element is a type element. Solution 1: And also a pure javascript solution: http://jsfiddle.net/M6qXZ/1/ 2018 ES6 Solution 2: By using If you alert above you will get the type of input element, then you can apply checks accordingly.

How to check element type in javascript

I have a situation in which i want to convert a tag into a and into bu using some condition. So how can i know that this element a type text or type select using id attribute.

2018 ES6

e => e.outerHTML = e.tagName === "INPUT" ? "  Solution 2: 

If you alert above you will get the type of input element, then you can apply checks accordingly.

Ref here : http://api.jquery.com/attr/

got from a link while searching not tested though.

You can use .is() to test whether the elements is of type x like

Use :text selector to test for text input element

Use element selector to test for select element

var elementType = $(«#myid»).prop(‘tagName’);

var inputType = $(«#myid»).attr(‘type’);

Javascript — Finding a form element’s type after finding it, Probably a dumb question, but is there a way in JavaScript to find out a form element’s type (text, checkbox, etc.) from a form element after finding it …

How to check the element type? [duplicate]

I am trying to determine if the selected element is a input type element.

var element = this.getElement(); console(element) => or something else 

How do I check if selected element is input element.

I searched google and someone said it can be

element.is(‘input’) but it gave me error saying is undefined.

Can anyone help me here? Thanks a lot!

If element is a DOM node, you could use it’s nodeName property.

var input = document.createElement('input') input.nodeName; //returns "INPUT" 

So, in your example, you could check if it is an input using element.nodeName === «INPUT»

Alternatively, you could do that with jQuery using $(element).is(‘input’) — although I wouldn’t use jQuery for such mundane tasks 🙂

Javascript — How to check an element type with chai?, 1 Answer. Well thats because chais type checking checks for javascript types, not for HTML-Tags. In case wrapper.find () returns a normal …

Finding the ‘type’ of an input element

I’d like to be able to find the type of something on the page using JavaScript. The problem is as follows: I need to check whether a specific area is a checkbox/radio button/ or text field.

If it’s a Checkbox or radio button it doesn’t have a length (no strings in it), otherwise if it’s a textfield I need to check whether or not it contains characters. The page is created dynamically so sometimes a checkbox may be displayed, other times a text field.

So my thinking is to find the type of the input, then determine what to do.

Any suggestions would be appreciated.

Check the type property. Would that suffice?

If you want to check the type of input within form, use the following code:

   

If you are using jQuery you can easily check the type of any element.

similarly you can check the other types and take appropriate action.

To check input type

   Try it function checktype()  

Javascript — Check if DOM Element is a checkbox, How can I check if a given DOM element is a a checkbox. Scenario: I have a set of textboxes and checkboxes in which the values are assigned …

Accessing elements by type in JavaScript

A while ago I was making some test in JavaScript, and played with a code to get the text of all elements with a certain class.

Now I was trying to make something like this but obtain all elements by a certain type, for example all elements type=»text»

Is there any way to do this in JavaScript or should I use jQuery?

var xx = document.getElementsByClassName("class"); for (i=0;i

If you are lucky and need to care only for recent browsers, you can use:

document.querySelectorAll('input[type=text]') 

«recent» means not IE6 and IE7

In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input'); for(var i = 0; i < inputs.length; i++) < if(inputs[i].type.toLowerCase() == 'text') < alert(inputs[i].value); >> 

In jQuery, you would just do:

// select all inputs of type 'text' on the page $("input:text") // hide all text inputs which are descendants of div input:text").hide(); 

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]'); 
var inputs = document.querySelectorAll("input[type=text]") || (function() < var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length; for (;i> return ret; >()); 

Javascript — How to get input type by element name, You can also get type property: var type = document.forms[«formQuestionnaire»].elements[«age»].type; It is somewhat …

Источник

Читайте также:  Http webtutor letoile ru view doc html mode my account
Оцените статью