Why are use the before and prepend method in JQuery? what is difference between the before and prepend method?

0 votes
74 views
Ethan Karla asked 28-Jul-2021 in Web Application by Ethan Karla

Why are use the before and prepend method in JQuery? what is difference between the before and prepend method?

1 Answer

1 votes
Ravi Vishwakarma answered 29-Jul-2021 by Ravi Vishwakarma
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.
Syntax

Before () 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:
Why are use the before and prepend method in JQuery? what is difference between the before and prepend method?