Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element by data selector in an array of HTML DOM objects using JavaScript?

I've an array of HTML DOM objects:

// Console output

(3) […]
0: <div data-selector="5">​
1: <div data-selector="9">​
2: <div data-selector="2">​
3: <div data-selector="6">​
4: <div data-selector="13">​
length: 5
<prototype>: Array []

How can I find (and return) the HTML object having data-selector equal to 9 (i.e.<div data-selector="9">​) using JavaScript?

like image 914
Backo Avatar asked Oct 27 '25 17:10

Backo


1 Answers

This would solve your problem.

array.find(item => item.dataset.selector === '9');

Explanation:

Javascript allows you to use dataset to access data attributes in html. That is, they have a pattern such as data-*

So, if you have a html file that looks like this:

<html>
  <div id="root">
    <div data-selector="5"></div>
    <div data-selector="9"></div>
    <div data-selector="2"></div>
    <div data-selector="6"></div>
    <div data-selector="13"></div>
  </div>
</html>

You can get the div with id of root in your javascript file:

const root = document.querySelector('#root');

// get array of div elements inside root
const tagsArray = [...root.children];

// finally, retrieve the specific element you need
const selectedItem = tagsArray.find(elem => elem.dataset.selector === '9');

// A simple check
console.log(selectedItem); // => <div data-selector="9"></div>
like image 75
Musonant Avatar answered Oct 29 '25 06:10

Musonant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!