Reputation: 63
I am trying to loop over all existing iframes by checking their attribute (name). In case it matches the name, I would like to set a src
value.
<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?
Upvotes: 1
Views: 5248
Reputation: 1295
I'm answering also if this already got an answer. This was it, vanilla js:
var selection = document.getElementsByTagName('iframe');
var iframes = Array.prototype.slice.call(selection);
iframes.forEach(function(iframe) {
if (iframe.name.match(/test1/g)) {
iframe.setAttribute("src", "http://testing1.com/");
} else if (iframe.name.match(/test2/g)) {
iframe.setAttribute("src", "http://testing2.com/");
} else if (iframe.name.match(/test3/g)) {
iframe.setAttribute("src", "http://testing3.com/");
}
});
JSFiddle here.
Upvotes: 5
Reputation: 1162
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>
Upvotes: 2
Reputation: 1067
A working example;
$(document).ready(function(e) {
$('iframe').each(function() {
if ($(this).attr('name') == "test1")
$(this).attr('src', 'https://www.domain1.com');
if ($(this).attr('name') == "test2")
$(this).attr('src', 'https://www.domain2.com');
if ($(this).attr('name') == "test3")
$(this).attr('src', 'https://www.domain3.com');
});
});
<iframe name="test1"></iframe>
<br>
<iframe name="test2"></iframe>
<br>
<iframe name="test3"></iframe>
Fiddle: https://jsfiddle.net/v760e5zq/
Upvotes: 0