Home > Enterprise >  How to get a list of the elements in a given div using JavaScript
How to get a list of the elements in a given div using JavaScript

Time:12-04

In a given id of a <div> I need to get a list of all the elements which are in that div.

My goal is to get a list of all elements in the given div and loop over them hide everyone except the first one.

Example:

<div id="RandomId">
    <img src="src_1" />
    <img src="src_2" />
    <img src="src_3" />
    .
    .
    .
    <img src="src_n" />
</div>

<script>
    function handleImages(divID) {
        const div = document.getElementById(DivID);
        if(div) {
            const Elements = // Here, I need the list;
            for (let i = 0; i < Elements.length; i  ) {
                if (i == 0) {
                    continue;
                }
                else {
                    Elements[i].style = "display:block";
                }
            }
        }
        return null;
    }
</script>

CodePudding user response:

You could also use querySelectorAll:

const Elements = document.querySelectorAll('#RandomId > img')

CodePudding user response:

You need to use Element.children to get the of elements inside the div.

CodePudding user response:

That's very easy to do when you're using native JavaScript. Use the following:

<script>
function handleImages(divID){
    const div = document.getElementById(DivID);
    if(div){

        const Elements = div.children //Here, I need the list;

        for (let i = 0; i < Elements.length; i  ){
            if (i == 0) { continue; }
            else {Elements[i].style = "display:block";}
        }
    }
    return null;

}
</script>

More details about Element.children.

CodePudding user response:

You can use querySelectorAll to get rid of first child as:

function handleImages(id) {
  const allChildren = [...document.querySelectorAll(`#${id} > img`)];
  allChildren.forEach(
    (imgChild, index) =>
    (imgChild.style.display = index === 0 ? "block" : "none")
  );
}
handleImages("RandomId");
<div id="RandomId">
  <img src="https://picsum.photos/200/300" />
  <img src="https://picsum.photos/200/300" />
  <img src="https://picsum.photos/200/300" />
  <img src="https://picsum.photos/200/300" />
</div>

CodePudding user response:

You can simplify your JS to this:

// Get the <div> element with the id "myDiv"
const myDiv = document.getElementById("myDiv");

// Use the querySelectorAll() method to get a list of all elements within the <div>
const elementsInMyDiv = myDiv.querySelectorAll("img");

// Loop over the elements in the list and hide each one (except for the first one)
for (let i = 1; i < elementsInMyDiv.length; i  ) {
  elementsInMyDiv[i].style.display = "none";
}

Note we start at index 1 instead of 0, which skips the first one as desired.

CodePudding user response:

You can do this

function handleImages(divID) {
  const div = document.getElementById(divID);

  if (div) {
    // Use the querySelectorAll() method to get the list of img elements in the div
    const elements = div.querySelectorAll('img');

    // Use the for...of loop to iterate over the elements
    // The first element (index 0) is skipped using the continue statement
    for (const element of elements) {
      if (element === elements[0]) {
        continue;
      }
      element.style = "display:block";
    }
  }

  return null;
}

This code uses the querySelectorAll() method to get the list of img elements in the div element, and it uses a for...of loop to iterate over the elements. This code is more concise and elegant than the original code, and it uses modern JavaScript features like the querySelectorAll() method and the for...of loop to make the code more readable and efficient.

  • Related