jQuery's context attribute usage instance

  • 2020-05-09 18:12:01
  • OfStack

This article illustrates the use of context properties for jQuery as an example. Share with you for your reference. The specific analysis is as follows:

This property can return the original DOM node content passed to jQuery(), the second parameter value of the jQuery() method.
If the jQuery() method does not specify this parameter, context points to the current document (document).
Grammatical structure:

$("selector").context

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
{
  width:150px;
  height:150px;
  border:1px solid blue;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  $("button").click(function(){
    alert($("li").context);
  })
})
</script> 
</head>
<body>
<div>
  <ul>
    <li> The test script </li>
  </ul>
</div>
<button> Click on the test </button>
</body>
</html>

By default, the original DOM node passed to jQuery() is Document, which returns [object] in IE and [object HTMLDocument] in other browsers.
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
{
  width:150px;
  height:150px;
  border:1px solid blue;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  $("button").click(function(){
    alert($("li",document.getElementById("myid")).context);
  })
})
</script>
</head>
<body>
<div>
  <ul id="myid">
    <li> The test script </li>
  </ul>
</div>
<button> Click on the test </button>
</body>
</html>

The return value of the above code is [object HTMLUListElement], but [object] in IE browser

I hope this article has been helpful to your jQuery programming.


Related articles: