Dynamically add a target attribute to a collection of existing anchor tags in a known div element

I have a div with id = "images".

The div contains some images that are wrapped in an anchor tag without a target attribute.

I would like to insert a script into my page, which pulls out a link to each of these anchor elements and declares the target = "new" attribute (at runtime) so that with each click they open in a new window.

I don’t want to hardcode the target attributes in the attached tags. This solution is for deployment after deployment. I do not use jquery in this application.

<div id="images"><a href=""><img src="foo.png" /></a>...etc </div> 
0
source share
4 answers

No jQuery required! You can do this easily using your own 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"; 
+2
source

You can move all the anchor elements inside your div by first looking at 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"; } 
0
source
 function replaceAllAnchors(Source,stringToFind,stringToReplace){ //sample call: body=replaceAllAnchors(body,'<a ','<a target="_blank" '); var temp = Source; var replacedStr=""; var index = temp.indexOf(stringToFind); while(index != -1){ temp = temp.replace(stringToFind,stringToReplace); replacedStr=replacedStr+temp.substr(0,temp.indexOf("/a>")+3); temp=temp.substr(temp.indexOf("/a>")+3); index = temp.indexOf(stringToFind); } replacedStr=replacedStr+temp; return replacedStr; } 
0
source

Why can't you use jQuery? I have added this here for other people who google.

This is 1 line of code in a loop:

 $('#images a').each(function(){ $(this).attr('target', '_blank'); }); 

Now not much easier? Use jQuery if you can.

0
source

Source: https://habr.com/ru/post/1390829/


All Articles