Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign an ID to a DIV using javascript

Tags:

jquery

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.

like image 643
Mauricio Avatar asked Nov 30 '25 10:11

Mauricio


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!