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>