0

I'm managing a tree of iFrames (all nested on a page) by id and src, so for a given src I can return an array of elements leading to this iFrame, like so:

["document", "123123", "dasd321"]

Since the number of elements in my array is dynamic, I would now like to construct a selector to retrieve the window to send a postMessage to. So I would need something like this:

document
    .getElementById("123123").contentWindow
    .getElementById("dasd321").contentWindow
    ...
    ... postMessage({"foo":"bar"}, window.location.href);

to be constructed dynamically.

Question:
Is it possible at all to generate a dynamic selector by looping over an array? If so or if not, how would I go about this?

Thanks!

3 Answers 3

1
target = ["document", "123123", "dasd321"].reduce (function (tgt, o) {
  return tgt && tgt.getElementById (o);
}, document);

should do the trick. returns null if any of your components do not exist

1
  • I also like this one! Thanks!
    – frequent
    Commented May 31, 2013 at 9:01
1

This could easily be done with:

["document", "123123", "dasd321"].forEach(function(o){
    document.getElementById(o).contentWindow //and so on
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FforEach

1
  • Yes. I added the MDN link for clarity. Commented May 31, 2013 at 8:11
1

You could use querySelectorAll:

var elements = ['#document', '#123123', '#dasd321'];
elements = document.querySelectorAll(elements.join(','));

[].forEach.call(elements, function(element) {
  // do something with `element`
});

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.