How to get div elements between a range of numbers?

Viewed 260

I want to get elements between a range of numbers, let's say between 10 and 15 from these:

<div class="1">....</div>
<div class="2">....</div>
<div class="3">....</div>
...
...
...
<div class="20">....</div>

Desired Output:

<div class="10">....</div>
<div class="11">....</div>
<div class="12">....</div>
<div class="13">....</div>
<div class="14">....</div>
<div class="15">....</div>
6 Answers

While the JS solution is probably better, mainly because it's more flexible, I want to mention the CSS solution, even though it has more limitations.

#parent {
  display: inline-block;
}
div {
  border: 1px solid #333;
  padding: 5px;
}
div div {
  width: 50px;
}
div:nth-child(n+10):nth-child(-n+15) { /* From the 10th child up to the 15th child */
  background-color: green;
}
<div id="parent">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
<div>07</div>
<div>08</div>
<div>09</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
<div>17</div>
<div>18</div>
<div>19</div>
<div>20</div>
</div>

By combining two nth-child selectors you can specify a range of elements. You can use this selector in JS as well

document.querySelectorAll('div:nth-child(n+10):nth-child(-n+15)');

The downside is that it will work well only if all the elements are siblings and the only children of the parent element.

The following example only works with this specific case where the classes are numbered. This is not a common scenario. Most would use unique IDs and then common Classes for grouping.

$(function() {
  function selectBetween(start, finish) {
    var selects = [];
    for (start; start <= finish; start++) {
      selects.push("." + start);
    }
    return $(selects.join(", "));
  }

  var myDivs = selectBetween(10, 15);
  console.log(myDivs.length);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">....</div>
<div class="2">....</div>
<div class="3">....</div>
<div class="4">....</div>
<div class="5">....</div>
<div class="6">....</div>
<div class="7">....</div>
<div class="8">....</div>
<div class="9">....</div>
<div class="10">....</div>
<div class="11">....</div>
<div class="12">....</div>
<div class="13">....</div>
<div class="14">....</div>
<div class="15">....</div>
<div class="16">....</div>
<div class="17">....</div>
<div class="18">....</div>
<div class="19">....</div>
<div class="20">....</div>

Console will show 6.

Just use slice will be sufficient.

[...document.getElementsByTagName("div")].slice(10,5)

[...document.querySelectorAll('div')]
  .filter((e) => Number(e.classList.value) >= 10)
  .filter((e) => Number(e.classList.value) <= 15)
  .map((e) => console.log(e.outerHTML))

 // <div class="10">....</div>
 // <div class="11">....</div>
 // <div class="12">....</div>
 // <div class="13">....</div>
 // <div class="14">....</div>
 // <div class="15">....</div>

Just map over an array of length of a number of elements required and use getElementsByClassName method to get the required elements between the range.

const getElements = (min, max) => {
  // construct an array of length of number of elements b/w min & max
  // and then map the required elements with the className selector
  return [...new Array((max - min) + 1)]
    .map((_, index) => document.getElementsByClassName(index + min));
}

console.log(getElements(10, 15));
<div class="0">0</div>
<div class="1">1</div>
<div class="2">2</div>
<div class="3">3</div>
<div class="4">4</div>
<div class="5">5</div>
<div class="6">6</div>
<div class="7">7</div>
<div class="8">8</div>
<div class="9">9</div>
<div class="10">10</div>
<div class="11">11</div>
<div class="12">12</div>
<div class="13">13</div>
<div class="14">14</div>
<div class="15">15</div>
<div class="16">16</div>
<div class="17">17</div>
<div class="18">18</div>
<div class="19">19</div>
<div class="20">20</div>

In order to get required output, first I would fetch all divs on the page, convert resulting nodelist into arrays so that I can apply arrays' filter method and then I would populate another div with outer HTML of the filtered arrays.

Here, I have created an arrow function which does filtering using parameters to make filter reusable. The code reads as under:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Div Elements from n number to n number</title>
    <script>

        window.onload = ()=>{

            // get all divs on this page
            let allDivs = document.querySelectorAll('div')

            // arrow function to get required divs where
            // start is int, stop is int and divs is nodelist
            const getDivsBetween = (start, stop, divs)=>{
                // convert nodelist to JavaScript array
                let theDivs = Array.from(divs)

                // filter the array 
                let retVal = theDivs.filter((element)=>{
                    // convert className to integer for checking
                    // whether className is between the values
                    let className = parseInt(element.className)

                    // return selected element
                    if (className >= start && className <=stop) return element 
                })

                return retVal // return array containing filtered elements
            }
            
            // get required divs
            let outPutDivs = getDivsBetween(10, 15, allDivs)

            // get div where output will go 
            let theOutputDiv = document.getElementById('output')

            // populate output div with filtered divs outer html
            // to get required output
            outPutDivs.map((element)=>{
                let thisDiv = document.createElement('div')
                thisDiv.append(element.outerHTML)
                theOutputDiv.append(thisDiv)
            })

        }
    </script>
</head>
<body>
    
    <div>Here are original divs</div>
    <div id="originals">
        <div class="1">....</div>
        <div class="2">....</div>
        <div class="3">....</div>
        <div class="4">....</div>
        <div class="5">....</div>
        <div class="6">....</div>
        <div class="7">....</div>
        <div class="8">....</div>
        <div class="9">....</div>
        <div class="10">....</div>
        <div class="11">....</div>
        <div class="12">....</div>
        <div class="13">....</div>
        <div class="14">....</div>
        <div class="15">....</div>
        <div class="16">....</div>
        <div class="17">....</div>
        <div class="18">....</div>
        <div class="19">....</div>
        <div class="20">....</div>
    </div>

    <hr>

    <div>Here is required output</div>
    <div id="output"></div>
    

</body>
</html>
Related