Simas Simas - 5 months ago 19
HTML Question

Javascript - loop over iframes and setting src

Well, basically what I'm trying to do - is writing a script that would loop over all existing iframes by checking their attribute (name). In case it matches the name, I would like to set a src.

<iframe name="test1" src="" />
<iframe name="test2" src="" />
<iframe name="test3" src="" />

<script>
$(document).ready(function(e) {
var frames = document.getElementByTagName('iframe');
for (var i in frames) {
if (frames[i].name.match(/test1/g)) {
iframes[i].attr('src', 'http://testing1.com/');
}
if (frames[i].name.match(/test2/g)) {
iframes[i].attr('src', 'http://testing2.com/');
}
}
};
</script>


would anyone help me to fix the code to make it valid?

Answer

Well, the function is getElementsByTagName (in plural). You're also mixing jQuery functions with native DOM elements, which won't work. But since you're using jQuery anyway, you might as well use it for all of the code:

<script>
$('iframe[name="test1"]').attr('src', 'testing1.com')
$('iframe[name="test2"]').attr('src', 'testing2.com')
</script>

Edit: also, iframes are not self closing tags, so you're going to get weird behaviour if you use <iframe /> like you did in your post. You should close the tag explicitly: <iframe></iframe>