Home >Web Front-end >Front-end Q&A >How to query child elements with jquery
How to query child elements in jquery: 1. Use the children() method to get the direct subset elements under the specified element; 2. Use the find() method to get all the elements under the specified element (including children). subset of a set) subset element.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jQuery child element selector find() and children()
children() method: Get the element The direct subset element under
find() method: Get all (including subsets of subsets) subset elements under this element
<html> <head> <meta charset="UTF-8"> <title>Document</title> <style> div{ /*background-color: pink;*/ } </style> </head> <body> <div> <span>11</span> <span> <ul> <li class="no1">aaa</li> <li>bbb</li> <li>ccc</li> </ul> </span> <span>222</span> <ul> <li>ddd</li> <li>eee</li> <li>fff</li> </ul> </div> </body> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $("div").children(".no1").css({color:'#a61c00',backgroundColor:"#0000ff"}); console.log($("div").children(".no1")[0]); // 打印获取到的dom元素 这时你会发现结果为 undefined // $("div").find(".no1").css({color:'#a61c00',backgroundColor:"#0000ff"}); </script> </html>
At this point we will open the find item and comment
<html> <head> <meta charset="UTF-8"> <title>Document</title> <style> div{ /*background-color: pink;*/ } </style> </head> <body> <div> <span>11</span> <span> <ul> <li class="no1">aaa</li> <li>bbb</li> <li>ccc</li> </ul> </span> <span>222</span> <ul> <li>ddd</li> <li>eee</li> <li>fff</li> </ul> </div> </body> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> // $("div").children(".no1").css({color:'#a61c00',backgroundColor:"#0000ff"}); // console.log($("div").children(".no1")[0]); $("div").find(".no1").css({color:'#a61c00',backgroundColor:"#0000ff"}); console.log($("div").find(".no1")[0]); </script> </html>
Corresponding screenshot:
Summarize the differences :
The children() method returns all direct child elements of the selected element (direct child elements, only sons and not grandchildren (: that is to say, no recursive traversal)
jQuery video tutorial, web front end】
The above is the detailed content of How to query child elements with jquery. For more information, please follow other related articles on the PHP Chinese website!