Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Append a Div in-between two Divs based on their ID's using Jquery?

If I have these objects:

<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='4'></div>
<div id='5'></div>

I have a textbox:

<input type="text">

Where I type in the value: 3.5 to dynamically make (I have the code for this, the next part I need help with):

<div id='3.5'></div>

How can I attach it in this order below, without first checking to see the value of every div on the page?

<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='3.5'></div>
<div id='4'></div>
<div id='5'></div>

Using:

$('#What Goes Here If I Dont know the elements on the page?').after('<div id='3.5'>Hey</div>');

Any help is appreciated,

Taylor

like image 407
TaylorMac Avatar asked May 13 '11 18:05

TaylorMac


People also ask

How append a div in another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.

How do I insert one div into another?

We can use . append() to do it like this: $('#old-block'). append('<div id="new-block-2"></div>');

What is insertAfter in jQuery?

jQuery insertAfter() Method The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.

Can you append to a div?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')


2 Answers

IDs in the DOM should not start with a number (they would not be valid).
They should start with a character A-Za-z and then they can have numbers, - and _ following.

but if you want to go your route try this:

var div = $("<div id='3.5'></div>");
div_id_after = Math.floor(parseFloat(div.get(0).id));

$('#'+div_id_after).after(div);

Here is a fiddle demo: http://jsfiddle.net/maniator/DPMV5/

like image 92
Naftali Avatar answered Sep 28 '22 09:09

Naftali


What is wrong with this ?

  $('#3').after('<div id='3.5'>Hey</div>');
like image 37
Shyju Avatar answered Sep 28 '22 09:09

Shyju