How to accept any characters between * from getElementById (stack_ * _overflow)?

I have a page that changes the identifier of the input fields each time. For example, if I visit the page now, the identifier could be "stack_15_overflow" , and next time it could be "stack_293_overflow" .

I want to use the substitution value for getElementById , for example "stack_ * _overflow" (where * corresponds to something) to get this value associated with any input field, starting and ending with a specific text, no matter what text is between them.

Code:

 function HelloId(string){ var name=string document.getElementById('stack_*_overflow').value=name; } 
+6
source share
4 answers
 var elements = document.querySelectorAll('[id^="stack_"][id$="_overflow"]'); 
+5
source

Using jQuery attribute starts with and attribute ends with selectors:

 $("[id^='stack'][id$=overflow]"); 

Note that these road selectors, specifying the type of an element can improve performance:

 $('element').filter("[id^='stack'][id$=overflow]"); 
+5
source

You cannot achieve this using getElementById . The best solution would be querySelector or querySelectorAll , where you get full support for CSS selectors.

Link in MDN

You will need these two attribute selectors:

Get items that start with a specific string

 document.querySelector('[id^="stack_"]'); 

Get items that contain a specific string

 document.querySelector('[id*="stack_"]'); 

Get items that complete with a specific string

 document.querySelector('[id$="_overflow"]'); 

By combining the final and starting selectors, you get the following and you can achieve the desired result:

 document.querySelector('[id^="stack_"][id$="_overflow"]'); 

Happy coding!

+2
source

Code:

 $("body:regex(id, stack_[0-9]+_overflow)"); 

using this plugin

0
source

Source: https://habr.com/ru/post/952523/


All Articles