jQuery Select # id with word as prefix and counter as suffix

后端 未结 3 2149
南旧
南旧 2021-02-20 14:56

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



        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 15:05

    Assuming you don't have millions of elements that start with "my", you could do:

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

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

提交回复
热议问题