查找属性在 class 中的所有元素

Find all elements with attribute in class

我想 select class main

中具有属性 [data-direction] 的所有元素
<div class="main">
   <div data-direction="top">1</div>
   <div data-direction="top">2</div>
   <div>3</div>
</div>
<div class="main">
   <div data-direction="top">3</div>
   <div>4</div>
   <div data-direction="top">5</div>
</div>

所以我可以 select 每个 div 和 data-direction 具体 class。类似于:main[x].style.top = '10px'

myElement = document.querySelectorAll('.main');
main = myElement.querySelectorAll('[data-direction]');

for (var i = 0; i < myElement.length; i++) {
    myElement[i].style.position = 'relative';

    for (var x = 0; x < parallaxStart.length; x++) {
      main[x].style.top = '10px';
    }
}

你需要:

document.querySelectorAll('.main').forEach((main) => {
  main.style.position = 'relative';
  main.querySelectorAll('[data-direction]').forEach((x) => {
    x.style.top = '10px';
  })
})

您可以将 forEachquerySelectorAll 一起使用,并记得指定元素,例如 div[data-direction]

const myElementArr = document.querySelectorAll('.main');
myElementArr.forEach(element => {
  element.style.position = 'relative';
  let mains = element.querySelectorAll('div[data-direction]');
  mains.forEach(main => {      
      main.style.top = '10px';
  });
});
<div class="main">
  <div data-direction="top">1</div>
  <div data-direction="top">2</div>
  <div>3</div>
</div>
<div class="main">
  <div data-direction="top">3</div>
  <div>4</div>
  <div data-direction="top">5</div>
</div>

参考:

您可以在循环内定位内部元素:

myElement = document.querySelectorAll('.main');

for (var i = 0; i < myElement.length; i++) {
    myElement[i].style.position = 'relative';
    var parallaxStart = myElement[i].querySelectorAll('[data-direction]');
    for (var x = 0; x < parallaxStart.length; x++) {
      parallaxStart[x].style.marginTop = '40px';
    }
}
<div class="main">
   <div data-direction="top">1</div>
   <div data-direction="top">2</div>
   <div>3</div>
</div>
<div class="main">
   <div data-direction="top">3</div>
   <div>4</div>
   <div data-direction="top">5</div>
</div>

只需在 .main class 中定位所有具有该数据属性的元素,然后使用 closest 并调整 main 的 CSS class.

const directions = document.querySelectorAll('.main [data-direction]');

directions.forEach(direction => {
  direction.classList.add('blue');
  direction.closest('.main').classList.add('embolden');
});
.embolden { font-weight: bold; }
.blue { color: blue; }
<div class="main">
  <div data-direction="top">1</div>
  <div data-direction="top">2</div>
  <div>3</div>
</div>
<div class="main">
  <div data-direction="top">3</div>
  <div>4</div>
  <div data-direction="top">5</div>
</div>