The jQuery before method is used to insert content into the HTML page before the selected elements. Appends the given content to a specific location in before ().
Same happens in prepend () it also appends the given data but like this child node.The prepend () method is used to insert the content at the beginning of the selected elements (as the first child).
The main difference between before() and prepare() is that before() adds the content first, but prepend() adds the content first treats like as a child.
SyntaxBefore () syntax
$(selector).before(content)
$(selector).before(content,function(index))Prepend () syntax
$(selector).prepend(content,function(index,html))
$(selector).prepend(content,function(index,html))
<!DOCTYPE html>
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('button').click(function(){
$('p').before('<p><b>Hello world! by before() </b></p>');
$('p').prepend('<p><b>Hello world! by prepend() </b></p>');
});
});
</script>
</head>
<body>
<button>Insert content by before() and prepend()</button>
<p>This is a paragraph.</p>
</body>
</html>
Output:
