In this article, we will explain to you how to add an element before another element using jquery. so we will give you a simple example of how to add an element before another element using jquery.

Example: jQuery insertBefore() method
In this example, we use jQuery insertBefore() method to add an element before the specific element. so you can follow the below example.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span>red</span>").insertBefore("p");
  });
});
</script>
</head>
<body>
<button>add span element before the p element</button>
<p>Color:- </p>

</body>
</html>

Example: jQuery before() method
In this example, we use jQuery before() method to add an element before the specific element. so you can follow the below example.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").before("<span>red</span>");
  });
});
</script>
</head>
<body>
<button>add span element before the p element</button><br/>
<p>Color:- </p>

</body>
</html>