如何通过JS条件语句实现页面特定文本的CSS隐藏?
Got it, let's get this working for you. Your current code only checks a string variable, but we need to connect that logic to actual elements on the page. Here's a complete, working solution:
Step 1: Full JavaScript Implementation
First, we'll write code that scans the page for elements containing your target text, then hides them. You can choose between adding a CSS class (more flexible) or directly setting inline styles.
// Define the exact text you want to hide const targetText = "Lease from 0%* or 0%*"; // Function to locate and hide matching elements function hideMatchingText() { // Scan all elements in the body (narrow this to specific tags like p/span/div if possible for better performance) const pageElements = document.body.querySelectorAll('*'); pageElements.forEach(element => { // Check if the element's text exactly matches your target (trim removes extra spaces) if (element.textContent.trim() === targetText) { // Option 1: Add a CSS class (recommended for maintainability) element.classList.add('hidden-target-text'); // Option 2: Directly hide the element (skip the CSS class if you prefer) // element.style.display = 'none'; } }); } // Run the function once the page is fully loaded window.addEventListener('load', hideMatchingText);
Step 2: Add CSS (if using the class approach)
If you went with Option 1 above, add this CSS to your stylesheet to hide the elements:
.hidden-target-text { display: none !important; }
Customization Tips
- If you need to hide elements that contain the target text (not just exact matches), replace
element.textContent.trim() === targetTextwithelement.textContent.includes(targetText). - To optimize performance, narrow down the
querySelectorAlltarget (e.g.,document.querySelectorAll('p, span, .text-container')) instead of scanning every element. - If you want to keep the element's space but make it invisible, swap
display: nonewithvisibility: hiddenoropacity: 0in the CSS.
Why Your Original Code Didn't Work
Your initial snippet only checked if a string variable had the letter "e"—it never connected to the actual elements on your page. The solution above bridges that gap by scanning page elements and acting on those that match your target text.
内容的提问来源于stack exchange,提问作者C Davies

