Reputation: 11
<html>
<body>
<div class = "myClass"></div>
<div class = "myClass"></div>
<div class = "myClass"></div>
<div class = "myClass"></div>
</body>
</html>
here i have a set of divs with class "myClass"..how can i put each one of them a specific id using jquery?
Here's what i wanted. i can't edit the html file..that's why i wanted to use jquery to add ids.
<html>
<body>
<div class = "myClass" id = "1"></div>
<div class = "myClass" id = "2"></div>
<div class = "myClass" id = "3"></div>
<div class = "myClass" id = "4"></div>
</body>
</html>
thank you in advance...
Upvotes: 0
Views: 119
Reputation: 18099
$('.myClass').uniqueId();
This will add Id to all elements of myClass class. Id will start with "ui-id-" Jsfiddle: http://jsfiddle.net/lotusgodkk/GCu2D/10/
Refer: uniqueId()
Upvotes: 2
Reputation: 543
var i = 0;
$('.myClass').each(function() {
i++;
$(this).attr('id', i); });
Upvotes: 2
Reputation: 1
You can add id by using of "index()". like below:
$('.myClass').each(function() {
$(this).attr('id',($(this).index()+1));
});
Upvotes: 0
Reputation: 388316
I think, you can use .attr() as given below
//dom ready handler
jQuery(function ($) {
$('.myClass').attr('id', function (idx) {
return idx + 1
})
});
Demo: Fiddle
Note: don't forget to include jQuery in your page
Upvotes: 0
Reputation: 67207
Try with .attr()
receiver function,
$('div.myClass').attr('id',function(i) { return "id" + i; });
Basically id with numeric values are not encouraged, so please prefix the numeric value with some alphabets.
Upvotes: 0
Reputation: 3373
var i = 0;
$('.myClass').each(function() {
$(this).attr('id', i++);
});
Upvotes: 0
Reputation: 20313
Use jquery .each()
and .attr()
. Try this:
$("div.myClass").each(function(i){
$(this).attr("id",i+1);
});
Upvotes: 2
Reputation: 38102
You can use .each() to itearate over the elements with class myClass
and .attr() to set the id
of targeted elements:
$('div.myClass').each(function(i) {
$(this).attr('id',i+1);
});
Also, id
start with number is an invalid HTML, you should do something like:
$('div.myClass').each(function(i) {
$(this).attr('id','div' + (i+1));
});
Upvotes: 1