0

If I have ten divs created dynamically, each one given the class name 'createdDiv' on creation. How can I iterate through them after they are created and add a unique class name to each?

Somthing like,

for each('.createdDiv'){
    var count = 1;
        this.addClass('uniqueName' + count);
        count ++;
}

So I would like to end up with 10 divs as follows,

('.createdDiv .uniqueName1')
('.createdDiv .uniqueName2')
('.createdDiv .uniqueName3')
('.createdDiv .uniqueName4')

and so on...

1
  • 2
    Because I'm asking to do it after creation. Commented Jan 31, 2014 at 17:47

4 Answers 4

3
$('.createdDiv').each(function(i){
    $(this).addClass('uniqueName' + i);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Much appreciated! I'll accept the answer 'in 4 minutes'. Cheers!
you're missing an );
1

Try

$('.createdDiv').addClass(function (i) {
    return 'uniqueName' + (i + 1)
})

Demo: Fiddle

2 Comments

Same question I asked Roko, why add one to the index?
@j08691 just because OPs index started from 1
1
$('.createDiv').each(function(i){
    $(this).addClass('uniqueName'+ (i+1));
});

4 Comments

Just curious, why add one to the index?
@j08691 cause index is 0 based, now take a look at the example in question... thought was correct
I'm not saying you're wrong, I just didn't know if there was any reason for doing it, other than to mimic the numbering in the question.
@j08691 well if he's adding numbered classes than I suppose it matters... but yes, '0' is also a number :D
0

This is not exactly what you're asking for, but another way to later access a list of generated elements would be to use the data attribute:

$(".createDiv").each(function(i){
    $(this).attr("data-index", i);
});

Then to select an element based on it's index:

$(".createDiv[data-index='" + i + "']")

Demo: Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.