当指定h2元素包含New Delhi文本时,如何隐藏目标DOM容器?
Solution to Hide Container Based on Heading Text
Let's break down how to implement your required conditional logic step by step:
Grab the target elements first
Always start by selecting the elements you need to work with, and add checks to ensure they exist before manipulation (this avoids console errors if the elements haven't loaded yet).// Get the h2 element that might contain "New Delhi" const cityHeading = document.querySelector("#flight-details-container > div:nth-child(1) > div.row.no-boot-md-mar > div > h2"); // Get the container we need to hide const adultPaxContainer = document.querySelector("body > div:nth-child(32) > div.fade.ssh-modal.ssr-modal.in.modal > div > div > div.modal-body > form > div.pax-row.adult > div:nth-child(3) > div");Add the conditional check and hiding logic
Now we'll verify if the heading exists and if its text includes "New Delhi". If both conditions are met, we'll hide the target container.if (cityHeading && cityHeading.textContent.includes("New Delhi")) { // Option 1: Directly hide via inline style adultPaxContainer.style.display = "none"; // Option 2: Add a CSS class (more maintainable - recommended!) // First define this class in your CSS: .hidden { display: none; } // adultPaxContainer.classList.add("hidden"); }
Key Notes:
- Element safety checks: The
cityHeading &&clause ensures we don't attempt to accesstextContenton anullelement if the selector fails to find a match. - Case sensitivity:
includes()is case-sensitive. If you need to match regardless of capitalization, usecityHeading.textContent.toLowerCase().includes("new delhi"). - Timing: Make sure this code runs after the DOM is fully loaded. You can wrap it in a
DOMContentLoadedevent listener, or place the script at the end of the<body>tag.
内容的提问来源于stack exchange,提问作者Ayaz Moeen
相关产品推荐
相关产品推荐

