I want to add a div as a first element using jquery on each click of a button
<div id='parent-div'> <!--insert element as a first child here ...--> <div class='child-div'>some text</div> <div class='child-div'>some text</div> <div class='child-div'>some text</div> </div>
We can also use the insertAdjacentElement method to insert an element as the first child of an element. to call insertAdjacentElement with 'afterbegin' and the newChild to prepend newChild as the first child element of the div.
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.
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
Try the $.prepend()
function.
$("#parent-div").prepend("<div class='child-div'>some text</div>");
var i = 0; $(document).ready(function () { $('.add').on('click', function (event) { var html = "<div class='child-div'>some text " + i++ + "</div>"; $("#parent-div").prepend(html); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="parent-div"> <div>Hello World</div> </div> <input type="button" value="add" class="add" />
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