select elements wich start with thesame name in javascript

To select elements that start with the same name in JavaScript, you can use the querySelectorAll method along with the ^= attribute selector. This will match all elements that have an attribute which name begins with a given substring.

index.tsx
const elements = document.querySelectorAll('[attribute^="substring"]')
71 chars
2 lines

Replace attribute with the name of the attribute, and substring with the starting substring of the attribute's value that you want to match.

For example, to select all elements that have a data- attribute which name starts with item-, you can use the following code:

index.tsx
const elements = document.querySelectorAll('[data^="item-"]')
62 chars
2 lines

This will return a NodeList of all elements that match this selector, which you can then loop through to perform further actions.

gistlibby LogSnag