The insertBefore() method in JQuery is used to insert HTML element right before an HTML element.
<html>
<head>
<title> My First Programme </title>
</head>
<body>
<h1> JQuery </h1>
<p>New Code</p>
<button> Click Here </button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script>
<script>
$('button').click( function() {
$("<p> This is a new paragraph </p>").insertBefore('p');
});
</script>
</body>
</html>
So, in the above code, we have to to add a new content <p> This is a new paragraph </p>, right before the <p> element,
<p>New Code</p>
And we have done it using the JQuery statement,
$('button').click( function() {
$("<p> This is a new paragraph </p>").insertBefore('p');
});So, on button click, the insertBefore() function is called,
$("<p> This is a new paragraph </p>").insertBefore('p');And the new content,
<p> This is a new paragraph </p>
Is added before,
<p>New Code</p>
Just note that This is a new paragraph is a new element that is added before the <p> element.
1.png)