Britt Jamrock
Britt Jamrock

Reputation: 35

Java Script Open Links within Multiple Divs in New Window

I'm having trouble getting some code working when using multiple div tags with different ids.

This code is in the head of an html document and working properly for a single div id:

<!-- Start External Links in New Window Requires div id article -->
<script type='text/javascript'>//<![CDATA[     
window.onload = function () {  
        var links = document.getElementById('article').getElementsByTagName('a');  
        for (var i = 0; i < links.length; i++) {  
            links[i].setAttribute('target', '_blank');}
        }  
//]]>  
</script>
<!-- End of External Links -->

I need this to work for multiple divs tags with different IDs on the same html page but the document.getElementById will only allow a single div ID.

I tried repeating the above code multiple times for each div but it only works with the very last iteration.

Does anyone know how to make the code work with multiple div tags with different ids?

Upvotes: 0

Views: 239

Answers (3)

Mehran Hatami
Mehran Hatami

Reputation: 12961

replace this part:

var links = document.querySelectorAll("#article a");

with:

var links = document.getElementById('article').getElementsByTagName('a');

this will result all the a tags in the node with 'article' id.

but if you have multiple article nodes, you better set the 'article' in 'class' attribute instead of setting as 'id'. then simply change the code like this:

var links = document.querySelectorAll(".article a");

and if the 'a' tags are in the first level of article nodes childnodes you can also do this:

var links = document.querySelectorAll(".article>a");

Upvotes: 0

Igor Benikov
Igor Benikov

Reputation: 897

For multiple divs you need to add class name, for example "article":

<div class="article"><a>one</a></div>
<div class="article"><a>two</a></div>

after this you can get elements by next way:

document.querySelectorAll('div.article>a')

Upvotes: 0

LorDex
LorDex

Reputation: 2636

change

var links = document.getElementById('article').getElementsByTagName('a');

to

var links = document.getElementsByClassName('your-class');

Upvotes: 1

Related Questions