At work I have a new site that makes use of iframes to embed external content onto a page. The content is a blog, written by non technical members of staff who needed to be able to include links to external websites. They are happy with using <a href="
tags, but I didn’t want to worry them with target parameters in the HTML. We have to target _blank
as we want the readers to keep the old site open and not open the content in the site framework.
The solution to this is to use a bit of JavaScript to manipulate the DOM and insert blank targeting to all blog entries.
As we control the HTML template of the blog, we made sure all the blog entries were wrapped by an enclosing div
tag with a class called blogentry.
Here’s some example HTML. We have one link in the blogentry div
we need to re target. The other link is not in a blogentry so has to be ignored.
<div class="blogentry">
<a href="http://www.robertprice.co.uk/">This link needs to open in a new window</a>.
</div>
<div>
<a href="http://www.robertprice.co.uk/">This link won't open in a new window</a>.
</div>
The JavaScript first has to get all div
tags on the page. It does this by calling getElementsByTagName
on the document. Once we have all the div
tags, we have to iterate over them to make sure we only get the ones with the classname of blog entry.
var entries = document.getElementsByTagName('div');
for (var i in entries) {
if (entries[i].className == "blogentry") {
// insert target code here.
}
}
Now have our blogentry’s we need to find all the links inside and make sure they all target blank. We do this by calling getElementsByTagName
on each node, then setting the target attribute to blank.
var targets = entries[i].getElementsByTagName('a');
for (var j in targets) {
targets[j].target="blank";
}
It’s as simple as that. The full code follows…
<script language="JavaScript" type="text/javascript">
<!--
var entries = document.getElementsByTagName('div');
for (var i in entries) {
if (entries[i].className == "blogentry") {
var targets = entries[i].getElementsByTagName('a');
for (var j in targets) {
targets[j].target="blank";
}
}
}
// -->
</script>