0

Am having two divs with same class name so when am attaching an element by creating id for both the divs, am getting the element id name as same for both the elements in both divs.

Example:

<div class="nav">
    <div class="example" id="example_1">
    </div>
</div>
<div class="nav">
    <div class="example" id="example_2">
    </div>
</div>

and I have used jquery syntax as

 $(".nav").append(example) 

where example_i increments.

How can I make different ids using jquery?

4 Answers 4

2

$('.nav').each(function(i,v){


$(this).append('<div id=example_'+i+'>example_'+i+'</div>')//use index of each .nav index starts at zero so if you need to start at 1 add 1 to index

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">

</div>
<div class="nav">

</div>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use something like this if you are not adding simple html strings. First make example a jQuery object, if it is not one already. Then you can easily manipulate the attributes.

var $example = $(example),
    idPre = 'example_',
    count = 1;
$(".nav").each(function() {
    $(this).append($example.clone().attr('id', idPre + count));
    count++;
})

Comments

0

A simplification of guradio's answer, append() can also take a function which returns the element based on the current index. This avoids the extra each() loop and recreating $(this).

$('.nav').append(function(i,v){

    //use index of each .nav index starts at zero so if you need to start at 1 add 1 to index
    return $('<div id=example_'+i+'>example_'+i+'</div>');

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">

</div>
<div class="nav">

</div>

Comments

0

This is the authentic answer, I tested it myself. You can use something like this if you are not adding simple html strings. First make the example a jQuery object, if it is not one already. Then you can easily manipulate the attributes.

var $example = $(example),
    idPre = 'example_',
    count = 1;
$(".nav").each(function() {
    $(this).append($example.clone().attr('id', idPre + count));
    count++;
});

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.