Iterating through all the instances with name having a common string [closed]

爷,独闯天下 提交于 2019-12-12 04:43:49

问题


Is there a way to access all the object instances starting with a common string.

Example: I have instances named button64, button223, button856471, button229846, etc. I have no control over how these instances are named. I want to push all these in an array.

I am not creating these objects, I just have to write a javascript which sits in this HTML page and collects all the object instances starting with the string 'button'.

The purpose is to reach out to a desired object out of these and change the visual element.

Also, the solution has to be compatible with IE8. Any ideas about how should I iterate?


回答1:


If you can use jQuery, you could write:

var buttonsArray = [];

$("div").each(function() {
    var id = $(this).attr("id");

    if (id && id.indexOf("button") == 0) {
        buttonsArray.push($(this));
    }
});



回答2:


You can use regular expressions to find any expression matching the pattern. Using the match method, every instance of the pattern is returned as an array.

var str = document.getElementById("sample");
var arr = string.match(/button[\d]*/g);

The regular expression on line two will match any result that has "button" and will stop once it encounters a character afterwards that is not a digit.



来源:https://stackoverflow.com/questions/22157209/iterating-through-all-the-instances-with-name-having-a-common-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!