JQuery Select # id with a word as a prefix and a counter as a suffix

Is there a way to select all id with jQuery with the prefix "my" and the suffix "0-9". Something like these $ ("# my $ 1-4") or is this possible with a loop?

<div id="my1"/> <div id="my2"/> <div id="my3"/> <div id="my4"/> <div id="my5"/> 
+6
source share
3 answers

First thoughts that seem to work well:

 $('div[id^="my"]').filter( function(){ return this.id.match(/\d+$/); }); 

JS Fiddle demo .

The above elements select all div elements whose id starts with my and then filters the returned elements to those whose id also ends with numeric characters.

Literature:

+13
source

The prefix part is easily reachable using the start-with selector attribute :

 $("div[id^=my]"); 

But there is no selector that allows you to specify a range of characters, so the loop should be involved. I would suggest filter :

 $("div").filter(function () { return /^my\d$/.test(this.id); }); 
0
source

Assuming you don’t have millions of elements that start with β€œmine,” you can do:

 $('[id^=my]').filter(function() { return this.id.matches(/\d/) && this.id.length == 3 }) 

This captures all elements that have an id starting with "my", contains a number and is only 3 characters long (so "my54" will not match, but "my6" will be)

0
source

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


All Articles