Method to select the third p element: 1. Use eq() to select the p element with index number 2, the syntax is "$("p").eq(2)"; 2. Use ":eq()" can select the p element with index number 2, and the syntax is "$("p:eq(2)")". Element index numbers are counted starting from 0, so the index number of the third element is 2.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery selects the third p element
1. Use the eq() method
The eq() method returns the element with the specified index number of the selected element. Index numbers start with 0, so the index number of the first element is 0 (not 1).
So selecting the third p element is to select the p element with index number 2.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p").eq(2).css({ "color": "red", "border": "2px solid red" }); }); }); </script> </head> <body> <div> <h2>标题</h2> <p>第1个p元素</p> <p>第2个p元素</p> <span>span元素</span> <p>第3个p元素</p> <p>第4个p元素</p> <p>第5个p元素</p> </div> <button>选择第三个p元素</button> </body> </html>
2. Use the “:eq()” selector
:eq() selector and eq() method Similarly, the element with the specified index is selected. Indexes also start at 0, so the index number of the first element is 0 (not 1).
Similarly, use :eq() to select the p element with index number 2.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p:eq(2)").css({ "color": "red", "border": "2px solid pink" }); }); }); </script> </head> <body> <div> <h2>标题</h2> <p>第1个p元素</p> <p>第2个p元素</p> <span>span元素</span> <p>第3个p元素</p> <p>第4个p元素</p> <p>第5个p元素</p> </div> <button>选择第三个p元素</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to select the third p element using jquery method. For more information, please follow other related articles on the PHP Chinese website!