Search code examples
javascripthtmlcustom-data-attribute

Find all elements with attribute in class


I would like to select all elements with attribute [data-direction] in class main

<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>

So I can select each div with data-direction in specific class. Something like: 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';
    }
}

Solution

  • You can target the inner elements inside the loop:

    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>