Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery insert div as certain index

Tags:

jquery

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!

like image 700
DantheMan Avatar asked Aug 25 '10 02:08

DantheMan


People also ask

What is insertAfter in jQuery?

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)

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.

Which jQuery DOM method is used to insert content after the selected elements?

The jQuery append() method inserts content AT THE END of the selected HTML elements.

How do I append my first child?

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.


1 Answers

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>
like image 67
Andy Gaskell Avatar answered Sep 21 '22 08:09

Andy Gaskell