javascript - 我如何将样式从一个类应用到另一个类,以及其间的所有项目
问题描述
我想在“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 类
是否可以将类添加到添加了背景颜色的所有内容中?作为替代解决方案?
解决方案
您需要跟踪两者之间的元素。像这样的东西:
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'
);
}
推荐阅读
- webpack - 如何避免在生产构建中给出垃圾名称
- python - 如何在 Mac 上正确安装 virtualenvwrapper?
- reactjs - 我有一个 react native 组件,我正在尝试通过 connect 将该组件连接到 react-redux,但出现错误
- android - 可运行与服务;用用例解释寿命
- javascript - 将文件从输入元素传递到 plupload(添加文件夹)
- ios - 这里有人知道如何解决“传递给不带参数的调用的参数”吗?
- html - 如何在标题上方制作段落层
- android - 每 5 分钟添加一次价值并重置 textview
- wordpress - Wordpress 的图像遮罩模块
- p5.js - 错误创建画布未定义-尝试保存示例项目时