Jquery find parent element child element of personal experience summary

  • 2020-03-30 02:37:21
  • OfStack

It is common to find parent and child elements using js or jquery. But always easy to use confusion, here unified summary, after use I believe it will be a lot more convenient

Methods: jquery up here to find the parent element used closest () parents () the parent ()

Find () children()

Js USES the children[] property

The HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>jquery Find the child element of the parent element </title> 


<div class="div1" id="div1" name="mydiv"> 
<p> The paragraph 1  Find the parent element </p> 
<table id="table1"> 

<tbody id="tbody1"> 
<td id="mytd1">11closest() Look up the nearest element (return zero or one element)  jQuery  Object) </td> 


<tr id="mytr2"> 
<td id="mytd2">21parent() methods </td> 

<td id="mytd3">31parent(" The selector ") methods </td> 



<div id="div2" style="border-bottom :5px;" name="mydiv"> 
<p> The paragraph 2  Find child elements </p> 
<table id="table2"> 
<td id="sectd1"> To find the table2 the td find() methods </td> 
<tr id="sectr2"> 
<td id="sectd2"> To find the table2 the td children() methods </td> 
<td id="sectd3">js the children[] Property to find </td> 



Js code:
<script type="text/javascript" src="./js/jquery-1.7.2.js"></script> 

//The closest () method
alert($(this).closest("table").attr("id")); //This is table1 instead of table0

//The parent () method
//alert($(this).html()); //$(this).html() is 21 (this).attr("id") is mytd2 
//.parent() is tr second. Parent is tbody. Even without the tbody tag, the third.parent() of the tbody is the table

//Document.write (" first parent id:" + $(this).parent().attr("id") + ". The second parent id is: "+ $(this). The parent (). The parent (). The attr (" id") + ". The third parent id is: "+ $(this). The parent (). The parent (). The parent (). The attr (" id"));


//Parent, parent, parent
$("p").parent("#div1").css("background", "yellow");//I've replaced it with a p tag. I don't know why I can't find the element with this
alert($(this).parents("div").attr("id"));//Div1 takes note of one parent parent

//Find td element in table2

var table = $("#table2"); 
//Children () is tbody children() is tr children("td[id='sectd2']") is td

//Js children []
var table = document.getElementById("table2"); 
//Children [0] is tbody children[2] is the third row tr children[0] is td


Related articles: