Get parent node, child node

1. Get a child node, such as a div element with an id of test, we select it like this, $('#test'), we want to find a span element with class demo under this div, there are several methods  1. Use Filter condition  $('#test span.demo')  2. Use the find() function  $('#test').find('span.demo')  3. Use the children() function  $('#test'). children('span.demo')  Second, get the parent node jquery has many methods to get the parent element, such as parent(), parents(), closest(), which can help you find the parent element or node  














 

copy code code show as below:

<ul class="parent1"> 
<li><a href="#" id="item1">jquery获取父节点</a></li> 
<li><a href="#">jquery获取父元素</a></li> 
</ul> 


Our purpose is to get the ul element whose class is parent1 through the note a whose id is item1. There are several methods: 

1.$('#item1').parent().parent('.parent1'); 

2. $('li:parent'); 

3.$('#items').parents('.parent1'); 

4.$('#items1').closest('.parent1'); 

closest will first check the current Whether the element matches, if so, the element itself is returned directly. If it doesn't match, look up the parent element, layer by layer, until you find an element that matches the selector. Returns an empty jQuery object if nothing is found. 

The main difference between closest and parents is: 1, the former starts matching and searching from the current element, and the latter starts matching and searching from the parent element; 2, the former searches upwards step by step until it finds a matching element, and the latter keeps searching upwards Until the root element, then put these elements into a temporary collection, and then use the given selector expression to filter; 3, the former returns 0 or 1 element, the latter may contain 0, 1, or more element. closest is useful for handling event delegation.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326924692&siteId=291194637