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?

4
  • will it be always added at the end? Commented Aug 6, 2014 at 7:56
  • what did you want to access, and how would you like to access it ( clicking the div or selecting from dropdownlist or other method ) Commented Aug 6, 2014 at 7:58
  • you can assign an Id when you are adding the div (some sort of counter id).. how are you adding the div. can you show more code. Commented Aug 6, 2014 at 8:00
  • Yes, it will always be added at the end. Commented Aug 6, 2014 at 8:00

3 Answers 3

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.

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

8 Comments

be careful doing this. class names dont like starting with numbers. stackoverflow.com/a/449000/648350
@haxxxton - Thanks for flashing light on class names. corrected my answer.
no probs :) similarly, this would be a great option for using id rather than class given we want them to be unique :)
@haxxxton - edited answer to include your suggestion.
How would I achieve this? With some kind of loop?
|
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"); }) }); 

2 Comments

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.
That should work! but btw, you did not mention that "divs can be deleted" in your question :-)
0

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

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

1 Comment

Can you write a little more code? I would use 'myid' with a number at the end i guess?!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.