Changing an element's ID with jQuery

2019-01-02 17:17发布

I need to change an element's ID using jQuery.

Apparently these don't work:

jQuery(this).prev("li").attr("id")="newid"
jQuery(this).prev("li")="newid"

I found out that I can make it happen with the following code:

jQuery(this).prev("li")show(function() {
    this.id="newid";
});

But that doesn't seem right to me. There must be a better way, no? Also, in case there isn't, what other method can I use instead of show/hide or other effects? Obviously I don't want to show/hide or affect the element every time, just to change its ID.

(Yep, I'm a jQuery newbie.)

Edit
I can't use classes in this case, I must use IDs.

9条回答
有味是清欢
2楼-- · 2019-01-02 17:35

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

查看更多
不流泪的眼
3楼-- · 2019-01-02 17:35
$("#LeNomDeMaBaliseID").prop('id', 'LeNouveauNomDeMaBaliseID');
查看更多
临风纵饮
4楼-- · 2019-01-02 17:41

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id","newId");
查看更多
浅入江南
5楼-- · 2019-01-02 17:47

What you mean to do is:

jQuery(this).prev("li").attr("id", "newID");

That will set the ID to the new ID

查看更多
怪性笑人.
6楼-- · 2019-01-02 17:54

A PREFERRED OPTION over .attr is to use .prop like so:

$(this).prev('li').prop('id', 'newId');

.attr retrieves the element's attribute whereas .prop retrieves the property that the attribute references (i.e. what you're actually intending to modify)

查看更多
高级女魔头
7楼-- · 2019-01-02 17:54

I did something similar with this construct

$('li').each(function(){
  if(this.id){
    this.id = this.id+"something";
  }
});
查看更多
登录 后发表回答