求助:JavaScript按星期控制元素显示,如何隐藏无内容的父容器?
Got it, let's tackle this problem straightforwardly. The core idea is to check if your target element contains the exact string "Not found any post", and if so, hide its parent container. Here's how to do it properly:
Step 1: Target the Element and Check Its Content
First, make sure you've correctly selected the element that shows the "Not found any post" message. Then, verify its trimmed text content matches the string (using trim() to avoid issues with extra whitespace):
// Replace with your actual selector (e.g., ID, class, or querySelector path) const noPostElement = document.getElementById('post-status'); if (noPostElement) { // Trim whitespace to handle cases where text has extra spaces/newlines const elementText = noPostElement.textContent.trim(); if (elementText === 'Not found any post') { // Hide the parent container const parentContainer = noPostElement.parentElement; // Option 1: Directly set display to none parentContainer.style.display = 'none'; // Option 2: Add a CSS class (recommended for better maintainability) // parentContainer.classList.add('hidden'); } }
Step 2: Use CSS Classes for Better Control (Optional but Recommended)
Instead of directly modifying the style property, define a CSS class to handle hiding. This keeps your styles centralized and easier to adjust later:
.hidden { display: none; }
Then in your JavaScript, use classList.add('hidden') instead of style.display = 'none' as shown in the comment above.
Step 3: Ensure the Code Runs After the Element is Rendered
If your content is loaded dynamically (e.g., fetched from an API or generated after the initial page load), wrap your code in a DOMContentLoaded event listener, or place it after the element is rendered in the HTML:
document.addEventListener('DOMContentLoaded', function() { // Your code from Step 1 goes here });
Edge Cases to Consider
- Element doesn't exist: The initial
if (noPostElement)check prevents JavaScript errors if the element isn't present in the DOM. - Whitespace in the text: Using
trim()ensures that extra spaces, tabs, or newlines don't break the string match. - Nested parent containers: If the parent container isn't the immediate parent, use
noPostElement.closest('.parent-container-class')instead ofparentElementto target the correct ancestor.
内容的提问来源于stack exchange,提问作者J Dorrian

