Categories
JavaScript Answers

How to return elements where ID begins with a certain string with JavaScript?

Spread the love

Sometimes, we want to return elements where ID begins with a certain string with JavaScript.

In this article, we’ll look at how to return elements where ID begins with a certain string with JavaScript.

How to return elements where ID begins with a certain string with JavaScript?

To return elements where ID begins with a certain string with JavaScript, we can select elements with querySelectorAll.

Then we can convert the returned node list into an array and use filter to return an array of elements with the given ID pattern.

For instance, we write:

<div id='foo1'>
  1
</div>
<div id='foo2'>
  2
</div>
<div id='bar'>
  3
</div>

to add divs with IDs.

Then we write:

const divs = document.querySelectorAll('div')
const fooDivs = [...divs]
  .filter(d => d.id.includes('foo'))
console.log(fooDivs)

We select all the divs with querySelectorAll.

Then we spread the divs into an array.

And then we call filter to return an array with the ones with ids that includes 'foo'.

Therefore, fooDivs should have the first 2 divs.

Conclusion

To return elements where ID begins with a certain string with JavaScript, we can select elements with querySelectorAll.

Then we can convert the returned node list into an array and use filter to return an array of elements with the given ID pattern.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *