How can I get the ID of an element using jQuery?

后端 未结 19 2544
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:57

Why doesn\'

相关标签:
19条回答
  • 2020-11-22 12:21

    id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

    $("#test").get(0)
    

    On this native element, you can call id, or any other native DOM property or function.

    $("#test").get(0).id
    

    That's the reason why id isn't working in your code.

    Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

    $("#test").attr("id")
    
    0 讨论(0)
  • 2020-11-22 12:22

    Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for window.jQuery

    if (window.jQuery) {
        $.prototype.id = function () {
            if (this.length > 1) {
                var val = [];
                this.each(function (idx, el) {
                    val.push($(el).id());
                });
                return val;
            } else {
                return this.attr('id');
            }
        }
    }
    

    It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.

    Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.

    0 讨论(0)
  • 2020-11-22 12:23

    $('selector').attr('id') will return the id of the first matched element. Reference.

    If your matched set contains more than one element, you can use the conventional .each iterator to return an array containing each of the ids:

    var retval = []
    $('selector').each(function(){
      retval.push($(this).attr('id'))
    })
    return retval
    

    Or, if you're willing to get a little grittier, you can avoid the wrapper and use the .map shortcut.

    return $('.selector').map(function(index,dom){return dom.id})
    
    0 讨论(0)
  • 2020-11-22 12:23
    $.fn.extend({
        id : function() {
            return this.attr('id');
        }
    });
    
    alert( $('#element').id() );
    

    Some checking code required of course, but easily implemented!

    0 讨论(0)
  • 2020-11-22 12:23

    .id is not a valid jquery function. You need to use the .attr() function to access attributes an element possesses. You can use .attr() to both change an attribute value by specifying two parameters, or get the value by specifying one.

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

    0 讨论(0)
  • 2020-11-22 12:23

    it does not answer the OP, but may be interesting to others: you can access the .id field in this case:

    $('#drop-insert').map((i, o) => o.id)
    
    0 讨论(0)
提交回复
热议问题