0

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?

sam
  • 11
  • 3
  • 1
    I know you can do this with jquery selector... Would be something like '$("[name^=button]")'... I'm not aware of a way to do it without jquery or something similar though... – user3334690 Mar 03 '14 at 20:58
  • http://stackoverflow.com/questions/9795773/get-variable-name-javascript-reflection look at @wingsofovnia answer. – Nimnam1 Mar 03 '14 at 21:01
  • I do not know the exact variable names. I know that they start with the string 'button'. Is there a solution in javascript? – sam Mar 04 '14 at 14:59

2 Answers2

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));
    }
});
  • Might make more sense to use `id.indexOf("button") == 0` since it should always appear at the start of the name. – Timothy Shields Mar 03 '14 at 21:00
  • If you're already including jquery then you could use a selector... [jQuery Doc: attribute starts with](http://api.jquery.com/attribute-starts-with-selector/) – user3334690 Mar 03 '14 at 21:03
0

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.

Nick Felker
  • 11,536
  • 1
  • 21
  • 35
  • I am looking for variables, not text within a string. How do I implement your solution to variable names? – sam Mar 04 '14 at 15:03