0

Lets say I have struckture like this:

<div id="stuff">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>

The divs will be dynamically added, meaning I cant say how much there will be.

When I rearrange the divs with jquery, is there a way to acces one of them even after they are moved? Is there some dynamically way to add an id to them and/or is there another way to achieve this?

3 Answers3

3

Give id to each div based on its sequence position like below:

<div>
  <div id='pos1'>1</div>
  <div id='pos2'>2</div>
  <div id='pos3'>3</div>
</div>

Then you can easily follow it using its position class irrespective its changed position.

alternatively you can use classes but they behaves slowly.

Pramod S. Nikam
  • 4,271
  • 4
  • 38
  • 62
0

You must give and id to your div when you dynamically creat them. Maybe with JQuery :

.attr("id","myid");
0

Just added a code snippet!

http://jsfiddle.net/q4273/

html:

<input class="btn teach_edit_header_buttons" style="font-family:Helvetica" type="submit" value="Add Div">
<div id='parent'></div>

js:

$(function () {

    $("input[type=submit]").click(function () {
        // get the available children
        var len = $('#parent').children('div').length;

        //determine the id = length+1
        var id = "item" + (len + 1);

        // append the child
        $("<div id='" + id + "'/>").html(id).appendTo("#parent");
   })

});
InnovWelt
  • 660
  • 1
  • 8
  • 21
  • thats great. When i wanted to delete a div I guess I would declare len before $("input[type=submit]").click(... and icrement it by one each time I add a new div?! Otherwise I could get two divs with the same id. – Ant1koerper Aug 06 '14 at 08:28
  • That should work! but btw, you did not mention that "divs can be deleted" in your question :-) – InnovWelt Aug 06 '14 at 08:57