R
R
romaro2021-07-14 02:31:51
JavaScript
romaro, 2021-07-14 02:31:51

How to get the names of all forms on the page as an array?

On different pages of the site there are forms with css classes whose names match the regular expression:
js-[a-z-]*-form

For example:

js-signup-form
js-create-product-form

I need to create a function that, when the page is loaded, will return an array of the names of these forms, i.e. will extract the string between "js-" and "-form":
[signup, create-product]

What's the best way to implement this? To look aside work with an HTML-collection?
Array.from(document.getElementsByTagName('p')).map((item) => item.innerHTML.replace('...', '...'))


If so, what is the best way to remove all unnecessary data from the code for each form?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-14
@romaro

Array
  .from(document.querySelectorAll('form'), n => [...n.classList])
  .flat()
  .map(n => n.match(/^js-([a-z-]*)-form$/)?.[1])
  .filter(Boolean)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question