Home  >  Article  >  Web Front-end  >  jquery sample code to get child nodes and parent nodes_jquery

jquery sample code to get child nodes and parent nodes_jquery

WBOY
WBOYOriginal
2016-05-16 17:22:541041browse
1. Get the child node

For example, it is a div element with the id of test. We select it like this, $('#test'), and we want to find a class under this div with the class demo There are several methods for span elements
1. Use filter conditions

$('#test span.demo')

2. Use find() function

$('#test').find('span.demo')

3. Use the children() function

$('#test').children('span. demo')

2. Get the parent node
jquery has many ways to get the parent element, such as parent(), parents(), closest(), these can help you achieve the search Parent element or node
Copy code The code is as follows:

Our purpose is to get the class through note a with the id of item1 For the ul element of parent1, there are the following methods:

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

2.$( 'li:parent');

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

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

closest will first check whether the current element matches, and if it matches, it will directly return the element itself. If there is no match, search upwards for the parent element, layer by layer, until an element matching the selector is found. If nothing is found, an empty jQuery object is returned.

The main difference between closest and parents is: 1. The former starts matching and searching from the current element, while 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 then stops. , the latter searches upwards until the root element, then puts these elements into a temporary collection, and then uses the given selector expression to filter; 3. The former returns 0 or 1 elements, and the latter may contain 0, 1, or multiple elements. closest is useful for handling event delegation.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn