简体   繁体   English

按模式查找ID(无jquery或3rd party库)

[英]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. 我看到了使用jquery的方法,但是我无法使用3rd party库。 How can I do this with pure javascript? 我该如何使用纯JavaScript?

You can use document.querySelectorAll() : 您可以使用document.querySelectorAll()

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

JSFiddle JSFiddle

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 JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM