Get specific elements

Hi

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?

Thanks

Try:

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

Something like this: https://jsfiddle.net/nbq130sk/2/

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

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

li[data-idx]:nth-child(n+2):nth-child(-n+4)

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(
    `[data-${name}]:nth-child(n+${from}):nth-child(-n+${to})`
  )
}

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

or

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

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)

2 Likes

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