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.
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;
});
.prop(), but in the .each(), I'd suggest skipping the method and using the property directly..attr and .prop can take functions as arguments to automatically loop .each for you, so you don't need the separate .each..each loop? You'd just change the code to this.id = "myid" + index.It's
$(document).ready(function(){
$(".myclass").eq(0).attr("id", "myid");
});
I wrote eq(0) because there cannot be two DOM elements with same ID, but there could be more than one .myclass
$(".myclass")[0].id = "myid";? Several less function calls and one less jQuery object.you can use .attr()
$(document).ready(function(){
$(".myclass").attr("id","myid");
});
fiddle : http://jsfiddle.net/LFQeR/