Ryzn
Ryzn

Reputation: 11

search elements by class and put id on each element in jquery

<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

Answers (9)

K K
K K

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

sir4ju1
sir4ju1

Reputation: 543

var i = 0;
$('.myClass').each(function() {
 i++;
 $(this).attr('id', i); });

Liveweave

Upvotes: 2

sandy
sandy

Reputation: 1

You can add id by using of "index()". like below:

$('.myClass').each(function() {
  $(this).attr('id',($(this).index()+1));    
});

Upvotes: 0

Arun P Johny
Arun P Johny

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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.

DEMO

Upvotes: 0

Tuhin
Tuhin

Reputation: 3373

var i = 0;
$('.myClass').each(function() {

 $(this).attr('id', i++); 
});

Upvotes: 0

Kiran
Kiran

Reputation: 20313

Use jquery .each() and .attr(). Try this:

$("div.myClass").each(function(i){
    $(this).attr("id",i+1);
});

DEMO

Upvotes: 2

Felix
Felix

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));    
});

Fiddle Demo

Upvotes: 1

Ajinkya
Ajinkya

Reputation: 22710

var count = 1;
$(".myClass").each(function(){
  $(this).attr("id", count);
  count++;
});

Fiddle

Upvotes: 1

Related Questions