1

I have the following block of jQuery code that I'm using to copy some html from one place to another:

var newLine  = $('#popup-clone .popup-contents').last().clone();
newLine.find('.popup-title').html("hello world");

$('#popup-container').append(newLine);

this runs in a loop several times so the html gets rendered like this:

    <div id="popup-container" style="display: block;">
        <div class="popup-contents">
            <a class="close">close this popup</a>
            <span class="popup-title">Title 1</span>
            <span class="popup-description"></span>
            <span class="popup-type"></span>
            <span class="popup-open"></span>
        </div>
        <div class="popup-contents">
            <a class="close">close this popup</a>
            <span class="popup-title">Title 2</span>
            <span class="popup-description"></span>
            <span class="popup-type"></span>
            <span class="popup-open"></span>
        </div>
    </div>

and so on

I want to add a unique ID to every div with class="popup-contents" but i'm not sure how i can do that? Any help is appreciated.

Felipe Kettle
  • 117
  • 1
  • 2
  • 14

4 Answers4

5

Use 'attr': http://api.jquery.com/attr/

newLine.attr('id', 'prefix' + someindex)
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
2

If the id can be unique random then what I've done in the past is used the UUID/GUID generator from Create GUID / UUID in JavaScript? to generate random ids.

Then it's just a matter of doing

newLine.attr( "id", guid );
Community
  • 1
  • 1
Marc Gagne
  • 819
  • 5
  • 7
1

You can generally avoid needing to giving cloned elements an id.

The reasons an element typically needs an id is (a) as a reference for CSS styling or (b) so it can be addressed by javascript/jQuery.

In both cases you can address the cloned element at the point it is created.

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
0

Use prop instead of attr:

jQuery .prop()

newLine.prop('id', 'prefix' + someindex)
Gabe
  • 49,577
  • 28
  • 142
  • 181