


How to locate nested child elements: implement the 'Show more' function
This article describes how to effectively locate target child elements nested in a multi-layer DOM structure when using jQuery to implement the Show More feature. It focuses on how to accurately find the elements that need to be operated through DOM traversal methods (such as parentNode and querySelector) or closest() methods when the target element is wrapped in an additional parent container, and provides code examples and precautions to help developers easily deal with complex DOM structures.
In web development, you often encounter situations where you need to manipulate DOM elements through JavaScript (especially jQuery). When the DOM structure is relatively simple, it is easy to find the target element using the selector directly. But when the DOM structure becomes complex and the elements are nested deep, how to accurately locate the target elements becomes a problem. This article will use a "Show More" function implementation as an example to explain in detail how to use jQuery to locate nested child elements.
Problem description
Suppose we have the following HTML structure, and we need to implement the function of clicking the "Show more" link, expanding or closing the content area:
<div class="text-container"> <h1>Title goes here</h1> <h2>Subtitle</h2> <div class="wrapper"> <div class="content hideContent"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diamond nonumy eirmod tempor involve ut labore et dolore magna aliquyam erat, sed diamond voluptua. At vero eos et accusam et just duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diamond nonumy eirmod tempor involve ut labore et dolore magna aliquyam erat, sed diamond voluptua. <p>Some more text</p> <ul> <li>Some more text</li> <li>Some more text</li> <li>Some more text</li> </ul> </div> </div> <div class="show-more"> <a href="#">Show more</a> </div> </div>
Among them, the initial state of the .content element is hidden (hideContent class). After clicking the .show-more a link, you need to switch the hideContent and showContent classes of the .content element and change the link text at the same time.
Solution
Traditional jQuery methods, such as $(this).parent().prev(".content"), may not be able to correctly find the target element after the DOM structure changes (for example, adding the .wrapper element). To solve this problem, we can use the following method:
1. Use parentNode and querySelector
This method traverses the DOM tree upwards through parentNode, finds a common parent element, and then uses querySelector to find the target element under the parent element.
$(".show-more a").on("click", function() { let div=this.parentNode.parentNode.querySelector('.content'); let classes=['showContent','hideContent']; if( div.classList.contains( classes[0] ) )div.classList.replace( classes[0],classes[1] ); else div.classList.replace( classes[1], classes[0] ); this.textContent = this.textContent=='Show more' ? 'Show less' : 'Show more'; });
This code first uses this.parentNode.parentNode to find the parent element of the .show-more, that is, the .text-container. Then, use querySelector('.content') to find an element with the class name content under .text-container.
2. Use the closest() method
The closest() method starts from the current element and looks up along the DOM tree until the first element matching the selector is found.
$(".show-more a").on("click", function() { var $this = $(this); var $content = $this.closest(".text-container").find(".content"); var linkText = $this.text().toUpperCase(); if (linkText === "SHOW MORE") { linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); } else { linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); }; $this.text(linkText); });
This code first uses $this.closest(".text-container") to find the .show-more a link to the nearest .text-container parent element. Then, use .find(".content") to find an element with the class name content under .text-container.
3. Use the parents() method
The parents() method returns all ancestor elements of the current element and can be used with the find() method.
$(".show-more a").on("click", function() { var $this = $(this); var $content = $this.parents(".text-container").find(".content"); var linkText = $this.text().toUpperCase(); if (linkText === "SHOW MORE") { linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); } else { linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); }; $this.text(linkText); });
This code first uses $this.parents(".text-container") to find all .text-container parent elements linked to .show-more a. Since there is only one .text-container parent element, parents() returns a jQuery object containing an element. Then, use .find(".content") to find an element with the class name content under .text-container.
CSS Style
In order for the Show More function to work properly, we need to define the styles of the showContent and hideContent classes:
.showContent{ display:block; } .hideContent{ display:none; }
Summarize
In complex DOM structures, accurately positioning target elements is key. The parentNode and querySelector methods provide precise search methods based on the DOM tree, while the closest() and parents() methods provide more flexible upward search methods. Which method to choose depends on the specific DOM structure and requirements. In actual development, it is recommended to prioritize the use of the closest() method because it is more concise and easy to understand.
Notes:
- When using parentNode, you need to ensure a clear understanding of the DOM structure and avoid error traversals.
- When using querySelector, you need to pay attention to the syntax of the selector to ensure that the target element can be matched accurately.
- When using the closest() and parents() methods, you need to pay attention to the performance of the selector to avoid affecting the performance of the page.
Through the study of this article, I believe you have mastered the common methods of positioning nested child elements in jQuery, and can easily deal with various complex DOM structures and achieve various interactive effects.
The above is the detailed content of How to locate nested child elements: implement the 'Show more' function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

Thenameattributeinaninputtagisusedtoidentifytheinputwhentheformissubmitted;itservesasthekeyinthekey-valuepairsenttotheserver,wheretheuser'sinputisthevalue.1.Whenaformissubmitted,thenameattributebecomesthekeyandtheinputvaluebecomesthevalueinthedatasen

❌Youcannotnesttagsinsideanothertagbecauseit’sinvalidHTML;browsersautomaticallyclosethefirstbeforeopeningthenext,resultinginseparateparagraphs.✅Instead,useinlineelementslike,,orforstylingwithinaparagraph,orblockcontainerslikeortogroupmultipleparagraph

ShadowDOM is a technology used in web component technology to create isolated DOM subtrees. 1. It allows the mount of an independent DOM structure on ordinary HTML elements, with its own styles and behaviors, and does not affect the main document; 2. Created through JavaScript, such as using the attachShadow method and setting the mode to open; 3. When used in combination with HTML, it has three major features: clear structure, style isolation and content projection (slot); 4. Notes include complex debugging, style scope control, performance overhead and framework compatibility issues. In short, ShadowDOM provides native encapsulation capabilities for building reusable and non-polluting UI components.

The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

To create an HTML unordered list, you need to use a tag to define a list container. Each list item is wrapped with a tag, and the browser will automatically add bullets; 1. Create a list with a tag; 2. Each list item is defined with a tag; 3. The browser automatically generates default dot symbols; 4. Sublists can be implemented through nesting; 5. Use the list-style-type attribute of CSS to modify the symbol style, such as disc, circle, square, or none; use these tags correctly to generate a standard unordered list.

ThecontenteditableattributemakesanyHTMLelementeditablebyaddingcontenteditable="true",allowinguserstodirectlymodifycontentinthebrowser.2.Itiscommonlyusedinrichtexteditors,note-takingapps,andin-placeeditinginterfaces,supportingelementslikediv
