Reputation: 147
I'm having an issue with changing the attribute for an id and can't seem to figure out what I'm doing wrong. I guess it doesn't help that I'm new to this also.
I have a function that tests to make sure that I am pulling the correct id from the row in my form that I have dynamically created. It goes something like this:
myFunction() {
var id = $(id).attr("id");
alert("This is my id " + id);
}
This works with no problem and when I click the button assigned to alert me of my id it will give me the id of the dynamic row in my form. The issue is now when I try to change the id with this:
changeId() {
var newId = $(id).attr("id", "x");
alert("This is my new id " + newId);
}
What happens in this case is that it will alert saying "This is my new id [object Object]" instead of giving me the new id. Any suggestions? I'd really appreciate any help with this.
Upvotes: 0
Views: 154
Reputation: 324507
Just change the id
property of the DOM node. Works in all browsers and couldn't be simpler:
var el = document.getElementById("your_id");
el.id = "new_id";
alert(el.id);
Upvotes: 1
Reputation: 630349
.attr(attribute, value)
returns the jQuery object again (so you can keep chaining), if you want that assigned ID, you need to do this:
changeId() {
var newId = $(id).attr("id", "x").attr("id");
alert("This is my new id " + newId);
}
Though the direct route is much better, for example:
changeId() {
var newId = "x"
$(id).attr("id", newId);
alert("This is my new id " + newId);
}
Upvotes: 5
Reputation: 38390
attr
when used to set an attribute returns the original jQuery object not the new attribute value.
Upvotes: 1
Reputation: 322452
Running .attr()
with one argument returns the value of the attribute.
Running .attr()
with two arguments returns the jQuery object against which it was called.
Docs: http://api.jquery.com/attr/
Upvotes: 1
Reputation: 338138
attr(name, value)
returns a jQuery object. This is to support jQuery method chaining.
You want
changeId() {
// ------------------------------v method chaining!
var newId = $(id).attr("id", "x").attr("id");
alert("This is my new id " + newId);
}
or simply
changeId() {
$(id).attr("id", "x");
alert("This is my new id " + id.id);
}
Maybe you also find a nicer name for the variable than id
.
Upvotes: 1
Reputation: 342625
You are setting, and not getting.The jQuery object is returned when you use .attr
to set an attribute - not the value you have set it to. Try:
changeId() {
$(id).attr("id", "x");
var id = $(id).attr("id");
alert("This is my new id " + newId);
}
Upvotes: 1