Say I have this:
<div id="controller"> <div id="first">1</div> <div id="second>2</div> </div>
but say I wanted to insert a new div arbitrarily based on an index I supply.
Say I gave the index to insert of 0, the result should be:
<div id="controller"> <div id="new">new</div> <div id="first">1</div> <div id="second">2</div> </div>
and if I have an index to insert of 2 the result would be.
<div id="controller"> <div id="first">1</div> <div id="second">2</div> <div id="new">new</div> </div>
and if I give an index of 1 the result would be:
<div id="controller"> <div id="first">1</div> <div id="new">new</div> <div id="second">2</div> </div>
just forget that last example's format. The simple act of copying and pasting HTML code on this site is horrific enough to make me about scream and pull my hair out and I dont want to spend anymore time messing with it!
The insertAfter() method is an inbuilt method in jQuery that is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Syntax: $(content).insertAfter(target)
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.
The jQuery append() method inserts content AT THE END of the selected HTML elements.
To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.
As a function with a little better handling of 0:
function insertAtIndex(i) { if(i === 0) { $("#controller").prepend("<div>okay things</div>"); return; } $("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>"); }
EDIT: Added parenthesis in the nth-child selector to avoid NaN errors. @hofnarwillie
function insertAtIndex(i) { if(i === 0) { $("#controller").prepend("<div>okay things</div>"); return; } $("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>"); } window.doInsert = function(){ insertAtIndex(2); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="controller"> <div>Item 1</div> <div>Item 2</div> <div>Item 4</div> <div>Item 5</div> </div> <button onclick="doInsert()">Insert "great things" at index 2.</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With