jQuery insertBefore() Method - CodingTag
×


jQuery insertBefore()

0 756

  • This jQuery method is used to add the given content before the selected HTML elements means this method insert a new element specified by the user before the every matched element.

Related Topics:

jQuery after
jQuery css

jQuery insertBefore()

Note:

before() and insertBefore() both jQuery methods are used for same work but the only difference between these methods is in their syntax.

Syntax:

$(content).insertBefore(selector);

Parameter description:

  • content: This represents the contents which to be insert before the selected elements. It is mandatory and must contain HTML tags. If the content is already exists on the webpage then it will be moved before the selected element.
  • selector: selector represents a jQuery selector that is used to select the HTML element before which the content to be inserted.
Note:

If you want to insert the content after the selected elements then use insertAfter() method.

Example:

In this example we insert a new paragraph before every <h3> tag.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para1{
background:yellow;
padding:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$text="<p class='para1'> This is the newly inserted paragraph before the heading. </p>";
$($text).insertBefore("h3");
});
});
</script>
</head>
<body>

<h2> jQuery insertBefore() method Example </h2>
<h3> This is heading1. </h3>
<h3> This is  heading2. </h3>
<button> Click me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Leave a Reply


Comments
    Waiting for your comments