Example of before of method usage in jQuery

  • 2020-05-09 18:07:31
  • OfStack

This article illustrates the use of the before() method in jQuery as an example. Share with you for your reference. The specific analysis is as follows:

This method appends HTML content to the outer front of each matched element.

Special note:

This method is to append the content, which means the original content is still there.
HTML content is content that can contain HTML tags and be rendered by the browser.
The text content first converts the HTML predefined characters in the content into html character entities so that the HTML label is not rendered.

Grammatical structure:

$(selector).before(content)

Example code:

Example 1:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<style type="text/css">
div
{
  height:150px;
  width:150px;
  background-color:green;
  margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("div").before("<b>  study hard </b>");
})
</script>
</head>
<body>
  <div></div>
</body>
</html>

Append the content to the original div content.

Example 2:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<style type="text/css">
div
{
  height:150px;
  width:150px;
  background-color:green;
  margin-top:10px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $("button").click(function(){
    $(".html").before("<b> study hard </b>");
    $(".text").text("<b> study hard </b>");    
  })
})
</script>
</head>
<body>
<div class="html"></div>
<div class="text"></div>
<button> Click to view </button>
</body>
</html>

With this example, you can observe the difference between HTML content and text content.

I hope this article has helped you with your jQuery programming.


Related articles: