It is often encountered when using js or jquery to find parent elements and child elements. However, it is always easy to be confused when using it. Here is a summary. I believe it will be much more convenient to use in the future
Here is the method used by jquery to find the parent element upward: closest() parents() parent()
Method used to search down child elements: find() children()
js uses the children[] attribute
html code
jquery finds parent element child element
< ;body>
Paragraph 1 Find parent element
11closest( ) Finds up to the nearest element (returns a jQuery object of zero or one element) |
21parent() method |
31parent("selector") method |
|
Find table2 The td children() method |
js's children[] attribute to find
|
tbody2222 |
js code:
<script> <br><br>$(function(){ <br>/************ Find parent element *************/ <br>//closest() method<br>$("#mytd1").bind("click",function(){ <br>//alert($(this).html()); <br>alert($(this).closest("table").attr("id")); //table1 instead of table0 <br>/ /alert($(this).closest("table").html()); <br>}); <br><br>//parent() method<br>$("#mytd2").bind ("click",function(){ <br>//alert($(this).html()); //$(this).html() is 21 (this).attr("id") is mytd2 <br>alert($(this).parent().parent().parent().attr("id")); <br>//.parent() is tr and the second .parent is tbody. There is no tbody tag, and the third .parent() found is table <br><br>//document.write("The id of the first parent:" $(this).parent().attr(" id") ". The id of the second parent is: " $(this).parent().parent().attr("id") ". The id of the third parent is: " $(this).parent ().parent().parent().attr("id")); <br><br>}); <br><br>//parent("selector") parents("selector") <br>$("#mytd3").bind("click",function(){ <br>$("p").parent("#div1").css("background", "yellow"); //The p tag is replaced here. I don’t know why the element cannot be found using this<br>//alert($(this).parent("#div").attr("id"));//undefined <br>alert($(this).parents("div").attr("id"));//div1 pay attention to a parent parents <br>}); <br><br><br>/************ Find child elements *************/ <br>//Find the td element of table2 find() <br>$("#sectd1").bind("click",function(){ <br>alert($("#table2") .find("td").length); <br>/* $("#table2").find("td").each(function(index,element){ <br>alert($(element). text()); <br>}); */ <br>}); <br><br>//children() <br>$("#sectd2").bind("click",function() { <br>var table = $("#table2"); <br>alert($("#table2").children().children().children("td[id='sectd2']"). html()); <br>//children() is tbody children() is tr children("td[id='sectd2']") is td <br>}); <br><br><br> // children[] of js <br>$("#sectd3").bind("click",function(){ <br>var table = document.getElementById("table2"); <br>alert(table. children[0].children[2].children[0].innerHTML); <br>//children[0] is tbody children[2] is tr in the third line children[0] is td <br>}) ; <br><br>}); <br></script>