Get specific elements


I have some DIVS each with attribute named ‘idx’, with unique value.

For example :

<div idx=0... <div idx=1... <div idx=2... ...

I would like to use querySelector (or any other method) to get al the DIVS that theirs ‘idx’ value
within a range of X and Y (for example 2 and 5 return 5 DIVS).
Now from for my understanding, I cannot use REGEX.

So, how can I solve this issue?



<div id=0... <div id=1... <div id=2... ... getElementById=("1")

Something like this:

If you want to get all divs you must use “class” and querySelectorAll and loop through the classes and search for a certain value.

Just having a look at a different approach using nth-child selectors

So say you have the following html

<ul id='items'>
  <li data-idx='1'>Item 1</li>
  <li data-idx='2'>Item 2</li>
  <li data-idx='3'>Item 3</li>
  <li data-idx='4'>Item 4</li>
  <li data-idx='5'>Item 5</li>
  <li data-idx='6'>Item 6</li>

You can select from the 2nd to the 4th idx elements with


Note: This isn’t going by the idx values, but rather the order of elements with an idx dataset attribute.

This could be turned into a javascript function

function selectDatasetRange (name, from, to, root = document) {
  return root.querySelectorAll(

const items = document.getElementById('items')
// select 1st to 3rd idx elements
const selected = selectDatasetRange('idx', 1, 3, items)

selected.forEach((elem) => elem.classList.add('red'))

is it

<div idx=0>
    <div idx=1>
        <div idx=2>


<div idx=0>
<div idx=1>
<div idx=2>

Because they require different algorithms.
And what is their parent element?

Yet another approach with [array]. May give some flexibility.

The second

My ignorance, but is this valid html <div idx=0> ? Or is it JSX or similar?

I was not familiar with the HTML datasets when I open this thread

No it’s invalid. :slight_smile: (but unlikely to do any harm)


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.