tags:

views:

33

answers:

2

I have a div with id="images".

The div contains some images that are each wrapped in an anchor tag with no target attribute.

I'd like to insert script into my page that pulls a reference to each of these anchor elements and ads a target="new" attribute to them (in the runtime) so that when they are clicked they each open in a new window.

I don't want to hardcode the target attributes on the anchor tags. This is a post deployment workaround. I'm not using jquery in this application.

<div id="images"><a href=""><img src="foo.png" /></a>...etc </div>
+1  A: 

No jQuery required! You can do this easily using native DOM methods:

// Find all the anchors you want to modify
var anchors = document.getElementById('images').getElementsByTagName('a'),
    i = anchors.length;

// Add the target to each one
while(i--) anchors[i].target = "new";
Prestaul
Thanks Prestaul, exactly what I was looking for.
Scott B
A: 

You can traverse all the anchor elements inside your div, first by looking up the div itself, and then you can use the element.getElementsByTagName method:

var imagesDiv = document.getElementById('images'),
    images = imagesDiv.getElementsByTagName('a');

for (var i = 0, n = images.length; i < n; i++) {
  images[i].target = "_blank";
}
CMS
Thanks CMS, this is exactly what I was looking for. Prestpaul just beat you to the punch by a few seconds :)
Scott B