Difference Between prepend() and before() in JQuery

In JQuery there are two methods prepend() and before() that is used to add data before selected element both method looks a like similar but there is little bit difference between them. Let’s see the difference:

1. prepend(): prepend method inserts the data at the top of its first child element.

Example:

<!DOCTYPE html> 
 <html> 
 <head> 
 </head> 
   
 <body> 
 <div class='main'> 
   <div class='child'>child</div> 
 </div> 
   
   
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
 <script> 
 $('.main').prepend($('<div class="firstchild">first child</div>')); 
 </script> 
 </body> 
 </html> 
   


Check this Example in Inspect Mode You will see the output like this :

This div: 
 
<div class="firstchild">first child</div>

Will be added before this div
<div class='child'>child</div>  


2. 
before(): This method inserts data before the selected element.

Example:

<!DOCTYPE html> 
 <html> 
 <head> 
 </head> 
   
 <body> 
 <div class='main'> 
   <div class='child'>child</div> 
 </div> 
   
   
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
 <script> 
 $('.main').before($('<div class="firstchild">first child</div>')); 
 </script> 
 </body> 
 </html>


Check this Example in Inspect Mode You will see the output like this :

This div:
<div class="firstchild">first child</div>
Will be added before this div
<div class='main'>child</div>  

Categories: web designing jquery

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 25 Days

Crash : 15 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Related Blogs

Request For Demo