1
var buttonArray = [
    document.getElementById('underline'),
    document.getElementById('bold'),
    document.getElementById('italic'),
    document.getElementById('tnr'),
    document.getElementById('ss'),
    document.getElementById('red'),
    document.getElementById('green'),
    document.getElementById('blue')
];

Can you do this? Or is it too abstract?

4
  • Can you do this... did you try? (Yes you can). Commented Feb 10, 2013 at 23:10
  • Have you tried running your code? Or are you trying to create elements instead of just selecting them? Commented Feb 10, 2013 at 23:10
  • You just did this: so yes. Commented Feb 10, 2013 at 23:11
  • 1
    Why don't you give all those elements the same class? Then it would be documents.getElementsByClassName('foo') or document.querySelectorAll('.foo'). But apart from that it will work fine. Commented Feb 10, 2013 at 23:13

1 Answer 1

2

Yes; that will work fine.

You can make it more elegant like this:

var buttonArray = [ "underline", ... ]
                  .map(document.getElementById.bind(document));
Sign up to request clarification or add additional context in comments.

6 Comments

Surely it's more elegant, but map and bind aren't widely supported yet so you'll need to shim them for older browsers. A simple for-loop to transform the tags into elements is always supported and still quite elegant.
@Slaks: Why do you need to call ultimately bind(document) on getElementById? I noticed that it won't work otherwise, but wouldn't document.getElementById already be bound to document?
@okiharaherbst: No; document.getElementById is a reference to an unbound function. this is set depending on the reference you call it from.
@SLaks: My bad, an immediate similarity with reflection in Java is, indeed, that the invoke(...) method on a Method object also takes an instance to call it (or bind it) upon as first argument. Many thanks anyway (reading up on bind() in JS – The definitive guide).
@okiharaherbst: Javascript has no equivalent to reflection. JS allows the function itself to be passed as an object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.