ChatGPT解决这个技术问题 Extra ChatGPT

Get element type with jQuery

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.

Can you rephrase? what do you mean by element type?

a
adeneo

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

Just remember that the .prop() function was only added in jQuery 1.6 - you may need to upgrade the version you're using!
This could be improved by switching 'tagName' to 'nodeName' as mentioned here.
@KyleStoflet - it seems you're right, nodeName does support more types of elements, and supporting IE5.5 shouldn't be an issue any more, so I see no issues with changing tagName to nodeName in the above answer. Both will work just fine for elements, and the latter will work on textnodes, attributes etc. as well.
Works but I got a bit confused by the prev(), which is specific for the example code in question. Basically, $(this).is("input");
@Fanky - That's correct, the OP is specifically asking for the previous element, hence then prev() call. The rest of the answer is applicable to any other circumstance where one might need to know the type of tag or check the tagname etc.
A
Ali

also you can use:

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

D
Distdev

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


An example would make this comment stronger.
J
James Toomey

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.


M
Mohammed Sufian

you can use .is():

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

see source


A
Amar

use get(0).tagName. See this link


c
coder

Use Nodename over tagName :

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

see DOM Core