What type of DOM Element?

前端 未结 6 1467
一个人的身影
一个人的身影 2020-12-14 14:34
e.g. if i have this:
whatever

then let say in jQuery, how can I find out that the dom element with id \"mydiv\"

相关标签:
6条回答
  • 2020-12-14 15:01
    alert($('#mydiv')[0].nodeName);
    
    0 讨论(0)
  • 2020-12-14 15:04

    Try is which tests if anything in the given set matches another selector:

    if( $('#mydiv').is('div') ){
      // it's a div
    }
    

    You can also get the tag this way:

    $('#mydiv').get(0).tagName // yields: 'DIV'
    
    0 讨论(0)
  • 2020-12-14 15:13

    $('#mydiv').get(0).nodeType if you know there's only one element. The selector object can contain an array of objects.

    .get() returns the array of DOM objects, the parameter indexes. nodeType is a property exposed by the DOM that tells you what the type of the DOM node is. Usually as a String in all caps IIRC.

    CORRECTION nodeType gives you an INT corresponding to a nodeType. tagName is what you want.

    0 讨论(0)
  • 2020-12-14 15:18
    var domElement = $('#mydiv').get(0);
    alert(domElement .tagName);
    

    may be of use.

    0 讨论(0)
  • 2020-12-14 15:21

    The .prop() function is a nice way of doing this.

    // Very jQuery
    $('#mydiv').prop('tagName');
    
    // Less jQuery
    $('#mydiv')[0].tagName;
    

    Both give the same result.

    And, as Aram Kocharyan commented, you'll probably want to standardise it with .toLowerCase().

    0 讨论(0)
  • 2020-12-14 15:24
    var type = $('#mydiv')[0].tagName
    
    alert(type);
    //displays "DIV"
    
    0 讨论(0)
提交回复
热议问题