如何使用jQuery获取元素的ID ?

时间:2022-11-27 11:47:00
<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

Why doesn't the above work, and how should I do this?

为什么上面的工作没有,我该怎么做呢?

17 个解决方案

#1


1716  

The jQuery way:

jQuery:

$('#test').attr('id')

In your example:

在你的例子:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

Or through the DOM:

或通过DOM:

$('#test').get(0).id;

or even :

甚至:

$('#test')[0].id;

and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

在JQuery中使用$('#test').get(0),甚至$('#test')[0]的原因是$('#test')是一个JQuery选择器,它返回的结果不是单个元素的默认功能。

an alternative for DOM selector in jquery is

jquery中的DOM选择器的另一种选择是。

$('#test').prop('id')

which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

它与.attr()和$('#test')不同。prop('foo')获取指定的DOM foo属性,而$('#test').attr('foo')获取指定的HTML foo属性,您可以在这里找到更多关于差异的细节。

#2


68  

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

$('selector').attr('id')将返回第一个匹配元素的id。参考。

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:

如果您的匹配集包含多个元素,则可以使用常规的.each迭代器返回包含每个id的数组:

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.

或者,如果您愿意得到一点grittier,您可以避免包装器并使用.map快捷方式。

return $('.selector').map(function(index,dom){return dom.id})

#3


35  

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)

id是html元素的属性。但是,当您编写$(“#something”)时,它会返回一个jQuery对象,该对象封装了匹配的DOM元素。要返回第一个匹配的DOM元素,调用get(0)

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

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

在这个本机元素上,可以调用id或任何其他本机DOM属性或函数。

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

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

这就是为什么id不能在代码中工作的原因。

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

或者,使用jQuery的attr方法作为其他答案,建议获得第一个匹配元素的id属性。

$("#test").attr("id")

#4


22  

Above answers are great, but as jquery evolves.. so you can also do:

以上的答案都很好,但是随着jquery的发展所以你也可以这样做:

var myId = $("#test").prop("id");

#5


19  

$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

Some checking code required of course, but easily implemented!

一些检查代码当然需要,但是很容易实现!

#6


9  

.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.

.id不是有效的jquery函数。您需要使用.attr()函数来访问元素所拥有的属性。您可以使用.attr()来通过指定两个参数来更改属性值,或者通过指定两个参数来获得值。

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

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

#7


5  

If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:

如果您想要获得元素的ID,让我们用类选择器来表示,当一个事件(在这个事件中单击事件)被触发在该特定元素上时,接下来将执行以下任务:

 $('.your-selector').click(function(){
       var id = $(this).attr('id');
 });

#8


4  

$('#test') returns a jQuery object, so you can't use simply object.id to get its Id

$('#test')返回一个jQuery对象,因此不能简单地使用对象。id来获取它的id。

you need to use $('#test').attr('id'), which returns your required ID of the element

您需要使用$('#test').attr('id'),它返回您所需的元素id。

This can also be done as follows ,

也可以这样做,

$('#test').get(0).id which is equal to document.getElementById('test').id

美元(#测试). get(0)。id = document。getelementbyid ('test')。id。

#9


2  

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

可能对找到这个线程的其他人有用。如果您已经使用了jQuery,下面的代码将只工作。函数返回始终是一个标识符。如果元素没有标识符,函数将生成标识符并将其附加到元素。

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

如何使用:

$('.classname').id();

$('#elementId').id();

#10


2  

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

嗯,似乎没有解决方案,我想提出我自己的解决方案,这是JQuery原型的扩展。我将它放入一个在JQuery库之后加载的Helper文件中,因此对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.

它可能不是完美的,但它可能会被纳入JQuery库。

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.

返回单个字符串值或字符串值数组。字符串值的数组,是用于事件的多元素选择器。

#11


2  

$('#test').attr('id') In your example:

$(" #测试”).attr(id)在你的例子:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

#12


1  

$('tagname').attr('id');

Using above code you can get id.

使用上面的代码可以得到id。

#13


1  

This is an old question, but as of 2015 this may actually work:

这是一个老生常谈的问题,但到2015年,这可能会奏效:

$('#test').id;

And you can also make assignments:

你也可以做作业:

$('#test').id = "abc";

As long as you define the following JQuery plugin:

只要您定义了以下JQuery插件:

Object.defineProperty($.fn, 'id', {
    get: function () { return this.attr("id"); },
    set: function (newValue) { this.attr("id", newValue); }
});

Interestingly, if element is a DOM element, then:

有趣的是,如果元素是DOM元素,那么:

element.id === $(element).id; // Is true!

#14


0  

Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:

重要:如果您正在使用jQuery创建一个新对象,并绑定一个事件,那么您必须使用prop,而不是attr,就像这样:

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");

$(“< div / >”,{ id:“yourId”类:“yourClass html:“< span > < / span > " })。(“点击”,函数(e){警报($(这).prop(" id "));}).appendTo(“#”);

#15


0  

This can be element id , class , or automatically using even

这可以是元素id、类,甚至可以自动使用。

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================

#16


0  

This will finally solve your problems:

这将最终解决你的问题:

lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.

假设页面上有多个按钮,您希望使用jQuery Ajax(或非Ajax)更改其中一个按钮,这取决于它们的ID。

lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.

我们还可以说,您有许多不同类型的按钮(用于表单、审批和类似目的),并且您希望jQuery只处理“like”按钮。

here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.

这里有一个工作的代码:jQuery只处理类的按钮。cls-hlpb,它将使用被单击的按钮的id,并根据来自ajax的数据更改它。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');
 alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",
    {
      name: "Donald Duck",
      city: "Duckburg"
    },
    function(data,status){

    //parsing the data should come here:
    //var obj = jQuery.parseJSON(data);
    //$("#"+id).val(obj.name);
    //etc.

    if (id=="btnhlp-1")
       $("#"+id).attr("style","color:red");
    $("#"+id).val(data);
    });
});




});
</script>
</head>
<body>

<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn">    </input>

</body>
</html>

code was taken from w3schools and changed.

代码取自w3schools,并进行了更改。

#17


0  

since the id is an attribut so you can get it by using the attr method

因为id是一个attribut,所以您可以通过使用attr方法获得它。

#1


1716  

The jQuery way:

jQuery:

$('#test').attr('id')

In your example:

在你的例子:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

Or through the DOM:

或通过DOM:

$('#test').get(0).id;

or even :

甚至:

$('#test')[0].id;

and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

在JQuery中使用$('#test').get(0),甚至$('#test')[0]的原因是$('#test')是一个JQuery选择器,它返回的结果不是单个元素的默认功能。

an alternative for DOM selector in jquery is

jquery中的DOM选择器的另一种选择是。

$('#test').prop('id')

which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

它与.attr()和$('#test')不同。prop('foo')获取指定的DOM foo属性,而$('#test').attr('foo')获取指定的HTML foo属性,您可以在这里找到更多关于差异的细节。

#2


68  

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

$('selector').attr('id')将返回第一个匹配元素的id。参考。

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:

如果您的匹配集包含多个元素,则可以使用常规的.each迭代器返回包含每个id的数组:

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.

或者,如果您愿意得到一点grittier,您可以避免包装器并使用.map快捷方式。

return $('.selector').map(function(index,dom){return dom.id})

#3


35  

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)

id是html元素的属性。但是,当您编写$(“#something”)时,它会返回一个jQuery对象,该对象封装了匹配的DOM元素。要返回第一个匹配的DOM元素,调用get(0)

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

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

在这个本机元素上,可以调用id或任何其他本机DOM属性或函数。

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

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

这就是为什么id不能在代码中工作的原因。

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

或者,使用jQuery的attr方法作为其他答案,建议获得第一个匹配元素的id属性。

$("#test").attr("id")

#4


22  

Above answers are great, but as jquery evolves.. so you can also do:

以上的答案都很好,但是随着jquery的发展所以你也可以这样做:

var myId = $("#test").prop("id");

#5


19  

$.fn.extend({
    id : function() {
        return this.attr('id');
    }
});

alert( $('#element').id() );

Some checking code required of course, but easily implemented!

一些检查代码当然需要,但是很容易实现!

#6


9  

.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.

.id不是有效的jquery函数。您需要使用.attr()函数来访问元素所拥有的属性。您可以使用.attr()来通过指定两个参数来更改属性值,或者通过指定两个参数来获得值。

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

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

#7


5  

If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:

如果您想要获得元素的ID,让我们用类选择器来表示,当一个事件(在这个事件中单击事件)被触发在该特定元素上时,接下来将执行以下任务:

 $('.your-selector').click(function(){
       var id = $(this).attr('id');
 });

#8


4  

$('#test') returns a jQuery object, so you can't use simply object.id to get its Id

$('#test')返回一个jQuery对象,因此不能简单地使用对象。id来获取它的id。

you need to use $('#test').attr('id'), which returns your required ID of the element

您需要使用$('#test').attr('id'),它返回您所需的元素id。

This can also be done as follows ,

也可以这样做,

$('#test').get(0).id which is equal to document.getElementById('test').id

美元(#测试). get(0)。id = document。getelementbyid ('test')。id。

#9


2  

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

可能对找到这个线程的其他人有用。如果您已经使用了jQuery,下面的代码将只工作。函数返回始终是一个标识符。如果元素没有标识符,函数将生成标识符并将其附加到元素。

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

如何使用:

$('.classname').id();

$('#elementId').id();

#10


2  

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

嗯,似乎没有解决方案,我想提出我自己的解决方案,这是JQuery原型的扩展。我将它放入一个在JQuery库之后加载的Helper文件中,因此对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.

它可能不是完美的,但它可能会被纳入JQuery库。

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.

返回单个字符串值或字符串值数组。字符串值的数组,是用于事件的多元素选择器。

#11


2  

$('#test').attr('id') In your example:

$(" #测试”).attr(id)在你的例子:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

#12


1  

$('tagname').attr('id');

Using above code you can get id.

使用上面的代码可以得到id。

#13


1  

This is an old question, but as of 2015 this may actually work:

这是一个老生常谈的问题,但到2015年,这可能会奏效:

$('#test').id;

And you can also make assignments:

你也可以做作业:

$('#test').id = "abc";

As long as you define the following JQuery plugin:

只要您定义了以下JQuery插件:

Object.defineProperty($.fn, 'id', {
    get: function () { return this.attr("id"); },
    set: function (newValue) { this.attr("id", newValue); }
});

Interestingly, if element is a DOM element, then:

有趣的是,如果元素是DOM元素,那么:

element.id === $(element).id; // Is true!

#14


0  

Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:

重要:如果您正在使用jQuery创建一个新对象,并绑定一个事件,那么您必须使用prop,而不是attr,就像这样:

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");

$(“< div / >”,{ id:“yourId”类:“yourClass html:“< span > < / span > " })。(“点击”,函数(e){警报($(这).prop(" id "));}).appendTo(“#”);

#15


0  

This can be element id , class , or automatically using even

这可以是元素id、类,甚至可以自动使用。

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================

#16


0  

This will finally solve your problems:

这将最终解决你的问题:

lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.

假设页面上有多个按钮,您希望使用jQuery Ajax(或非Ajax)更改其中一个按钮,这取决于它们的ID。

lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.

我们还可以说,您有许多不同类型的按钮(用于表单、审批和类似目的),并且您希望jQuery只处理“like”按钮。

here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.

这里有一个工作的代码:jQuery只处理类的按钮。cls-hlpb,它将使用被单击的按钮的id,并根据来自ajax的数据更改它。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');
 alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",
    {
      name: "Donald Duck",
      city: "Duckburg"
    },
    function(data,status){

    //parsing the data should come here:
    //var obj = jQuery.parseJSON(data);
    //$("#"+id).val(obj.name);
    //etc.

    if (id=="btnhlp-1")
       $("#"+id).attr("style","color:red");
    $("#"+id).val(data);
    });
});




});
</script>
</head>
<body>

<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn">    </input>

</body>
</html>

code was taken from w3schools and changed.

代码取自w3schools,并进行了更改。

#17


0  

since the id is an attribut so you can get it by using the attr method

因为id是一个attribut,所以您可以通过使用attr方法获得它。