How to insert element as a first child?

119,908

Solution 1

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

Solution 2

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

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

Solution 3

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

Solution 4

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).

Solution 5

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

Share:
119,908

Related videos on Youtube

Rana Imtiaz
Author by

Rana Imtiaz

I'm a learner and love to help others. My main role in ASP.Net Development, Jquery, Vuejs, Scala development. I have been working since 2006 in C# and now playing as a full stack developer and working in Vue js and Scala.

Updated on July 08, 2022

Comments

  • Rana Imtiaz
    Rana Imtiaz over 1 year

    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> 
    
  • Aurovrata
    Aurovrata over 5 years
    this will insert before each child, ie you will end up inserting multiple nodes.
  • Aurovrata
    Aurovrata over 5 years
    there are not children nodes below child-div
  • Aurovrata
    Aurovrata over 5 years
    this will insert multiple nodes, one before each child.
  • Aurovrata
    Aurovrata over 5 years
    the problem with this solution is that it inserts as the first child and not before the list children, if the parent container contains different children elements and one wants to insert before a specific group of child nodes, this will not work.

Related