最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jquery - Javascript add div to top of another div - Stack Overflow

matteradmin4PV0评论

I want to add a div element at the top inside another div element.

<div class="chat-box" id="chat-box">
    <div class="item">
        <img src="avatar.png"/>
        <p class="message">
        <a href="#" class="name"><small class="text-muted pull-right"><i class="fa fa-clock-o">Date</i></small></a>
        Message
        </p>
    </div>
</div>

I need to add new "item" divs above the ones that are already there. Is there any jquery or javascript snipped that does this for me?

Thanks for the help! :)

I want to add a div element at the top inside another div element.

<div class="chat-box" id="chat-box">
    <div class="item">
        <img src="avatar.png"/>
        <p class="message">
        <a href="#" class="name"><small class="text-muted pull-right"><i class="fa fa-clock-o">Date</i></small></a>
        Message
        </p>
    </div>
</div>

I need to add new "item" divs above the ones that are already there. Is there any jquery or javascript snipped that does this for me?

Thanks for the help! :)

Share Improve this question asked Mar 16, 2014 at 13:50 user3425765user3425765 2911 gold badge4 silver badges12 bronze badges 1
  • .prepend() – Patrik Krehák Commented Mar 16, 2014 at 13:53
Add a ment  | 

2 Answers 2

Reset to default 5

.append() will append it at the end of #chat-box.

.prepend() will pre-pend it, at the beginning of it, like what you're trying to achive.

var new_item_html = "<div class='item'>i am an item</div>"
$("#chat-box").prepend(new_item_html);

hope that helps.

In general the div's display is in their order. Any additional div will be the last on top. Use in the div's style position:absolute

Post a comment

comment list (0)

  1. No comments so far