Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

jquery - How to insert element as a first child?

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> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...