Get element type with jQuery

JqueryElement

Jquery Problem Overview


Is it possible, using jQuery, to find out the type of an element with jQuery? For example, is the element a div, span, select, or input?

For example, if I am trying to load values into a drop-down list with jQuery, but the same script can generate code into a set of radio buttons, could I create something like:

$('.trigger').live('click', function () {
   var elementType = $(this).prev().attr(WHAT IS IT);
});

Given a drop-down list with a button next to it with the trigger class, my elementType variable should return select upon the button being pressed.

Jquery Solutions


Solution 1 - Jquery

Getting the element type the jQuery way:

var elementType = $(this).prev().prop('nodeName');

doing the same without jQuery

var elementType = this.previousSibling.nodeName;

Checking for specific element type:

var is_element_input = $(this).prev().is("input"); //true or false

Solution 2 - Jquery

also you can use:

$("#elementId").get(0).tagName

Solution 3 - Jquery

you should use tagName property and attr('type') for inputs

Solution 4 - Jquery

As Distdev alluded to, you still need to differentiate the input type. That is to say,

$(this).prev().prop('tagName');

will tell you input, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use

$('#elementId').attr('type');

to tell you checkbox/text/radio, so you know what kind of control it is.

Solution 5 - Jquery

you can use .is():

  $( "ul" ).click(function( event ) {
      var target = $( event.target );
      if ( target.is( "li" ) ) {
         target.css( "background-color", "red" );
      }
  });

see source

Solution 6 - Jquery

use get(0).tagName. See this link

Solution 7 - Jquery

Use Nodename over tagName :

> nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.

see DOM Core

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamie HartnollView Question on Stackoverflow
Solution 1 - JqueryadeneoView Answer on Stackoverflow
Solution 2 - JqueryAliView Answer on Stackoverflow
Solution 3 - JqueryDistdevView Answer on Stackoverflow
Solution 4 - JqueryJames ToomeyView Answer on Stackoverflow
Solution 5 - JqueryMohammed SufianView Answer on Stackoverflow
Solution 6 - JqueryAmarView Answer on Stackoverflow
Solution 7 - JqueryMike RifginView Answer on Stackoverflow