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

如何在JavaScript中像Sass那样结合循环使用querySelectorAll?

JavaScript中的列表遍历(类似Sass的@each)

Absolutely! You can totally replicate that list-based iterative workflow you use in Sass right in JavaScript—and your existing code snippet is already heading in the perfect direction. Let’s break this down clearly, compare it to your Sass example, and expand on practical use cases.

First, map your Sass knowledge to JavaScript

In Sass, you use @each to loop through a list and generate CSS rules for each item:

$list: item-1, item-2, item-3; 
@each $item in $list { 
  .#{$item} { 
    // Styles for each item class
  } 
}

In JavaScript, this translates directly to using an array (your notificationTypes variable) and the forEach() method (your loop)—this is the exact equivalent of Sass’s list + @each combo.

Your code is on the right track—let’s polish it

First, quick note: you had a small typo (succes → success) in your array, so let’s fix that first. Then, let’s add concrete functionality to make it actionable:

const notificationTypes = ["alert", "info", "success", "warning"];

// Loop through each notification type (like Sass @each)
notificationTypes.forEach(function(type) {
  // Find all elements with the current type's class
  document.querySelectorAll(`.${type}`).forEach(function(el) {
    // Example 1: Add a base "notification" class for shared styles
    el.classList.add('notification');

    // Example 2: Apply type-specific background colors
    switch(type) {
      case 'alert':
        el.style.backgroundColor = '#dc3545';
        break;
      case 'info':
        el.style.backgroundColor = '#17a2b8';
        break;
      case 'success':
        el.style.backgroundColor = '#28a745';
        break;
      case 'warning':
        el.style.backgroundColor = '#ffc107';
        el.style.color = '#212529'; // Dark text for contrast
        break;
    }

    // Example 3: Add a click handler to dismiss the notification
    el.addEventListener('click', function() {
      el.style.opacity = '0';
      setTimeout(() => el.style.display = 'none', 300);
    });
  });
});

If you want to generate CSS rules (like Sass does at compile time)

If your goal is to dynamically create CSS classes (instead of modifying existing DOM elements), you can even generate a <style> tag with JavaScript—this mimics how Sass compiles list loops into static CSS, but does it dynamically at runtime:

const notificationTypes = ["alert", "info", "success", "warning"];
const dynamicStyle = document.createElement('style');
let cssRules = '';

// Build CSS rules for each type
notificationTypes.forEach(type => {
  // Base notification styles
  cssRules += `
    .${type} {
      padding: 12px 16px;
      border-radius: 4px;
      margin: 8px 0;
      color: white;
      cursor: pointer;
      transition: opacity 0.3s;
    }
  `;

  // Type-specific background colors
  switch(type) {
    case 'alert':
      cssRules += `.${type} { background-color: #dc3545; }`;
      break;
    case 'info':
      cssRules += `.${type} { background-color: #17a2b8; }`;
      break;
    case 'success':
      cssRules += `.${type} { background-color: #28a745; }`;
      break;
    case 'warning':
      cssRules += `.${type} { background-color: #ffc107; color: #212529; }`;
      break;
  }
});

// Add the generated CSS to the page
dynamicStyle.textContent = cssRules;
document.head.appendChild(dynamicStyle);

Key differences from Sass

  • Sass’s @each runs at compile time to generate static CSS files.
  • JavaScript’s forEach runs in the browser at runtime, so it can react to dynamic data, user interactions, or changes to the DOM after the page loads.

Your initial approach is perfect for interacting with existing DOM elements, while the dynamic <style> method is great if you need to generate styles on the fly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:42:45