3

I have set of buttons like this:

<button id="grid1_createBtn">Create</button>
<button id="grid1_updateBtn">Update</button>
<button id="grid2_createBtn">Create</button>
...

These button does not have any class, so I need to select them via their ID. The "grid" part of id is static and same for all buttons. I found this answer, but I don't want to use ​$("[id^=grid]"), because may be some other other element with starting id "grid" exist. Can anyone help me?

Community
  • 1
  • 1
hamed
  • 7,939
  • 15
  • 60
  • 114

4 Answers4

6

To select the buttons with a regular expression, you may use filter like this :

$('button').filter(function(){
    return /^grid\d+_\w+Btn$/.test(this.id)
})
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Try this:

var id= 1;
$("button[id*='grid" + id+ "_createBtn']");
Rohit Arora
  • 2,246
  • 2
  • 24
  • 40
0

You may also combine attribute selectors like below as long as all your buttons start with grid and end with Btn.

$('button[id^="grid"][id$="Btn"]')

-A Demo-

lshettyl
  • 8,166
  • 4
  • 25
  • 31
0

You can combine!

$("[id^='grid'][id$='Btn']")

$("[id^='grid'][id$='Btn'][id*='_']")

or you can mix with Denis Seguret aproach

$("button[id^='grid']").filter( 
    function(){
        return /^grid\d+_(create|update)Btn$/.test(this.id);
    }
)

this is faster than only the filter.

Raúl Martín
  • 4,471
  • 3
  • 23
  • 42