jQuery before() Method - CodingTag
×


jQuery before()

1166

  • 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 css
jQuery val

jQuery before

Syntax:

$(selector).before(content,function(index));

Parameter description:

  • content: This represents the contents which to be insert before the selected elements. It can be either plain text or it may contain HTML tags. It is a mandatory parameter. Possible values for this parameter are:
  • 1 HTML elements

    2 DOM elements

    3 jQuery objects

  • function(index): This represents a function which used to return the content to insert. It is optional.
  • index: This parameter is used to get the index position of the element in the set.
Note:

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

Example:

In this example we insert a new paragraph before the each <h3> element.

<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:pink;
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.</p>";
$('h3').before($text);
});
});
</script>
</head>
<body>

<h2> jQuery before() 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:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments