Simon Erasmus
Simon Erasmus

Reputation: 134

Using plain JavaScript to list only direct child elements

I am trying to list the img elements in my slideshow using JavaScript, which is all children in a container. In that container I also have 2 divs for the navigating arrows. They also contain a child img element.

How do I only list the first set of img elements and not the nav arrows as well using plain JavaScript?

      <div id='imgContain'>
        <?php
        $path = "./resSlide";
        $all_files = scandir($path);
        $how_many = count($all_files);
          for ($i=2; $i<$how_many;$i++) {
                $num=$i-1;
                echo "<img src=\"./resSlide/$all_files[$i]\" id= \"$num\" class= \"slideImg2\"/>";
          }   
        ?>
        <div id='imgPosbar'>
          <div id='imgPosbarIn'></div>
        </div>
        <div id='imgPosLeftBut' onclick='LeftClick();'>
          <img class='imgBut' src="leftarrow.png" alt='Sorry'>
        </div>
        <div id='imgPosRightBut' onclick='RightClick();'>
          <img class='imgBut' src='rightarrow.png' alt='Sorry'>
        </div>
      </div>

Upvotes: 0

Views: 1482

Answers (1)

Asons
Asons

Reputation: 87231

This will select all img which is a direct child of the #imgContain

var elems = document.querySelectorAll('#imgContain > img');

for (var i = 0; i < elems.length; i++) {
    // do something with each img
    var el = elems[i];
}

Upvotes: 2

Related Questions