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,681
  • 13
  • 50
  • 104

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
  • 355,860
  • 83
  • 755
  • 726
0

Try this:

var id= 1;
$("button[id*='grid" + id+ "_createBtn']");
Rohit Arora
  • 2,206
  • 2
  • 23
  • 39
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,016
  • 4
  • 23
  • 30
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,026
  • 2
  • 20
  • 39