Rana Imtiaz
Rana Imtiaz

Reputation: 1413

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> 

Upvotes: 123

Views: 145786

Answers (8)

Sayed
Sayed

Reputation: 631

$('.parent-div').children(':first').before("<div class='child-div'>some text</div>");

Upvotes: 1

Gibolt
Gibolt

Reputation: 47237

parentElement.prepend(newFirstChild);

This is a new addition in (likely) ES7. It is now vanilla JS, probably due to the popularity in jQuery. It is currently available in Chrome, FF, and Opera. Transpilers should be able to handle it until it becomes available everywhere.

P.S. You can directly prepend strings

parentElement.prepend('This text!');

Links: developer.mozilla.org - Polyfill

Upvotes: 5

Chintan7027
Chintan7027

Reputation: 7605

Required here

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

added by

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

Upvotes: 0

dtsn
dtsn

Reputation: 1107

Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).

ParentNode.insertBefore(<your element>, ParentNode.firstChild);

Upvotes: 25

Mohamed Nuur
Mohamed Nuur

Reputation: 5655

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

Upvotes: 197

Varun Bhatia
Varun Bhatia

Reputation: 4396

parentNode.insertBefore(newChild, refChild)

Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

Upvotes: 6

THAS
THAS

Reputation: 9

$(".child-div div:first").before("Your div code or some text");

Upvotes: -1

WizxX20
WizxX20

Reputation: 321

Use: $("<p>Test</p>").prependTo(".inner"); Check out the .prepend documentation on jquery.com

Upvotes: 7

Related Questions