Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>  
like image 332
Rana Imtiaz Avatar asked Dec 24 '10 18:12

Rana Imtiaz


People also ask

How do you add elements to your first child?

We can also use the insertAdjacentElement method to insert an element as the first child of an element. to call insertAdjacentElement with 'afterbegin' and the newChild to prepend newChild as the first child element of the div.

How do I add a div to my first child?

To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.

What is first child in HTML?

The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.


1 Answers

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" />
like image 87
Mohamed Nuur Avatar answered Sep 20 '22 01:09

Mohamed Nuur