首页 > 解决方案 > 我如何将样式从一个类应用到另一个类,以及其间的所有项目

问题描述

我想在“day-start”和“day-end”之间的所有子元素上添加特定的样式属性

在此处输入图像描述

我试过使用这样的代码:

document.querySelectorAll('.day').forEach(
el => el.querySelectorAll('div').forEach(
el => el.style.color = 'red'
)
);

但不确定如何在这两个类之间添加它

使用 jQuery 解决方案:

 $(".day-start").nextUntil(".day-end").addClass("foo");

将类添加到正确的元素,但在表格行标记上中断 + 它不包括 .day-start + .day-end 类

是否可以将类添加到添加了背景颜色的所有内容中?作为替代解决方案?

标签: javascriptjquerycssdomcss-selectors

解决方案


您需要跟踪两者之间的元素。像这样的东西:

let section = 0; // our flag: 0 - before, 1 - in-between, 2 - after

document.querySelectorAll('.day').forEach(
    el => {
        if (section === 0 && el.classList.contains('day-start')) {
            section = 1;
        } else if (section === 1 && el.classList.contains('day-end')) {
            section = 2;
            // now, if this was a loop, we could simply `break;` it 
            // but `forEach` doesn't offer that
        }

        if (section === 1) { // we apply this logic only for divs in section 1
            el.querySelectorAll('div').forEach(
                div => div.style.color = 'red'
            )
        }
     }
);

使用循环,它会更简单一些:

let isBefore = true;

for (const el of document.querySelectorAll('.day')) {
    if (isBefore && el.classList.contains('day-start')) {
        isBefore = false;
    } else if (el.classList.contains('day-end')) {
        break; // we're ending all iteration here
    }

    if (isBefore) continue; // we finish the current round here, and go to another `el`

    el.querySelectorAll('div').forEach(
        div => div.style.color = 'red'
    );
 }

推荐阅读