user2924127
user2924127

Reputation: 6252

Find id by pattern (Without jquery or 3rd party libraries)

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?

Upvotes: 1

Views: 80

Answers (2)

b00t
b00t

Reputation: 419

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

Upvotes: 1

George
George

Reputation: 36794

You can use document.querySelectorAll():

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

JSFiddle

Upvotes: 3

Related Questions