I'm trying to assign an ID to a DIV that already has a Class attached to it. Here's my code: (The class is "myclass" and the id is "myid")
$(document).ready(function(){
$(".myclass").id("myid");
});
Thanks in advance.
Try with .prop() if you use jQuery 1.6+ or .attr() otherwise:
$(".myclass").prop("id", "myid");
If you have more than one element with that class, it will assign same ID to multiple elements which is very bad practice.. in this case append the index:
$(".myclass").each(function(index) {
$(this).prop("id", "myid" + index);
});
Edit:
Most elegant and efficient way is using .prop() or .attr() (in pre 1.6) directly without .each() then assigning the id of the direct DOM element:
$(".myclass").prop("id", function(index) {
return "myid" + index;
});
Live test case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With