Assuming I have the following divs:
<div id="mydiv">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
How can I in jquery or javascript make it such that I can append an element right after the first child of "mydiv". Or is there some selector to allow me to select and append after the first child?
<div>
<div>1</div>
<div>Place to Insert Subsequent div</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
JavaScript – Insert Element after Specific Div Element To insert element in document after div element using JavaScript, get reference to the div element; call after() method on this div element; and pass the element to insert, as argument to after() method.
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.
First, select the ul element by its id ( menu ) using the getElementById() method. Second, create a new list item using the createElement() method. Third, use the insertAfter () method to insert a list item element after the last list item element.
The jQuery after() method is used to insert content after the selected elements.
You can do this using :first-child
and after
:
$("#mydiv div:first-child").after(newDiv);
Demo
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