How to insert element as a first child?

Rana Imtiaz picture Rana Imtiaz · Dec 24, 2010 · Viewed 102.1k times · Source

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> 

Answer

Mohamed Nuur picture Mohamed Nuur · Dec 24, 2010

Try the $.prepend() function.

Usage

$("#parent-div").prepend("<div class='child-div'>some text</div>");

Demo

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" />