Method: 1. Use "$(element).children()" to get the child element object of the element; 2. Use "child element object.not(":first")" to get the first child Child element objects outside the element; 3. Use "Child element object except the first child element.remove()" to delete the child elements and keep the first one.
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
1. Use children to obtain child elements
The children() method returns the selected element All direct child elements.
DOM tree: This method only traverses a single level down the DOM tree. To traverse down multiple levels (returning descendant nodes or other descendants), use the find() method.
Tip: To traverse a single level up the DOM tree, or to traverse all paths up to the root element of the document (returning parent nodes or other ancestors), use the parent() or parents() method.
The syntax is:
$(selector).children(filter)
2. Use not to cooperate: first to exclude the first child element
not() method returns no Elements that meet certain conditions.
This method lets you specify a condition. Elements that do not meet the criteria will be returned from the selection, and elements that meet the criteria will be removed.
This method is usually used to remove one or more elements from the selected element combination.
:first selector selects the first element.
The syntax is
$(":first")
3. Use remove to delete elements
remove() method removes the selected elements, including all text and child nodes.
This method will also remove the data and events of the selected element.
The syntax is:
$(selector).remove()
The example is as follows:
123/title> body (曾祖先节点)div (祖先节点)ul (直接父节点)
- li (第一个子节点) span (孙节点)
- li (第二个子节点) span (孙节点)
- li (第三个子节点) span (孙节点)
- li (第四个子节点) span (孙节点)
Output result:
Related video tutorials Recommended:jQuery video tutorial
The above is the detailed content of How to delete child elements in jquery and keep the first one. For more information, please follow other related articles on the PHP Chinese website!