You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

满足特定条件时为元素添加active类的代码故障排查

Hey there! Let's troubleshoot why your code isn't working as intended. Let's start by breaking down your requirements clearly, then walk through the most common mistakes that might be causing the issue:

Your goal is:

  • Check if the <body> has a class that starts with hotel-stores (like hotel-stores, hotel-stores-1, etc.)
  • If that's true, and the element with id="dropdown-menu" has the active class
  • Then add the active class to the element with id="39"

Here are the most likely issues and fixes:

1. You're checking for the exact hotel-stores class (not variants)

If you used document.body.classList.contains('hotel-stores'), this only matches the exact class name. It won't catch variants like hotel-stores-1 or hotel-stores-2.

To fix this, you need to check if any class on the body starts with hotel-stores:

const hasHotelStoresClass = [...document.body.classList].some(cls => cls.startsWith('hotel-stores'));

2. Your code runs before the DOM is fully loaded

If your script runs before the elements (#dropdown-menu and #39) are rendered in the DOM, getElementById will return null, and none of your logic will execute.

Wrap your code in a DOMContentLoaded listener to ensure it runs after the DOM is ready:

document.addEventListener('DOMContentLoaded', function() {
  // Your logic goes here
});

3. You're using an incorrect selector for the id="39" element

While document.getElementById('39') works fine, if you used querySelector('#39'), you'll run into issues because CSS selectors don't allow IDs starting with numbers without escaping.

If you prefer querySelector, you need to escape the number:

const targetElement = document.querySelector('#\\39');

But getElementById('39') is simpler and safer here.

4. You're not listening for dynamic class changes on #dropdown-menu

If the active class is added to #dropdown-menu after your initial code runs (e.g., via a click event), your code won't re-trigger to update #39.

Use a MutationObserver to watch for changes to the #dropdown-menu's class attribute, so your logic runs whenever the active class is added/removed:

Full Working Example

Putting it all together, here's a robust solution:

document.addEventListener('DOMContentLoaded', function() {
  // Check if body has any class starting with "hotel-stores"
  const bodyHasTargetClass = [...document.body.classList].some(cls => cls.startsWith('hotel-stores'));
  
  if (!bodyHasTargetClass) return; // Exit early if body doesn't meet the condition

  const dropdownMenu = document.getElementById('dropdown-menu');
  const targetElement = document.getElementById('39');

  // Function to update the target element's class
  function updateTargetElement() {
    if (dropdownMenu.classList.contains('active')) {
      targetElement.classList.add('active');
    } else {
      // Optional: Remove "active" if dropdown loses it
      targetElement.classList.remove('active');
    }
  }

  // Run once on page load
  updateTargetElement();

  // Watch for changes to dropdown-menu's class attribute
  const observer = new MutationObserver(updateTargetElement);
  observer.observe(dropdownMenu, { attributes: true, attributeFilter: ['class'] });
});

This code covers all your requirements, handles dynamic class changes, and ensures it runs at the right time.

内容的提问来源于stack exchange,提问作者Eduardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:46:35