0

I have a button:

<button id="btn:1:uniquenamehere">btn</button>

the number in the middle sometimes changes due to other frameworks internal workings. I need to be able to find this button no matter the number in the middle. So I need to find it by pattern where only the middle number will change. So I need something like this:

document.getElementById("btn:*:uniquenamehere")

I saw ways of doing it using jquery, but I can't use 3rd party libraries. How can I do this with pure javascript?

user2924127
  • 6,034
  • 16
  • 78
  • 136
  • Can you not just add a class to those buttons and then look them up by their class name ? – htatche Jul 08 '15 at 18:48
  • 1
    Take a look [at this question](http://stackoverflow.com/q/12566888/1685196) or [this one](http://stackoverflow.com/q/6991494/1685196) – Michel Jul 08 '15 at 18:52

2 Answers2

2

You can use document.querySelectorAll():

var elems = document.querySelectorAll('[id$="uniquenamehere"]');

JSFiddle

George
  • 36,413
  • 9
  • 66
  • 103
0

Also, if you'd like to fool around a bit, this is a good (if not as efficient) way:

function getButton (buttonid) {
    var buttons = document.getElementsByTagName('button');
    for (var i = 0; i < buttons.length; i += 1) {
        if (buttons[i].id.slice(buttons[i].id.length - buttonid.length) === buttonid) {
            return buttons[i];
        }
    }
    return null;
}

JSFiddle

b00t
  • 409
  • 3
  • 10