简体   繁体   中英

Add target blank to JavaScript generated link

The script is used in a php file and it diplays a linked alexa rank image:

<script type="text/javascript" src="http://xslt.alexa.com/site_stats/js/t/a?url=x-invest.net"></script>

This is the result:

<a class="AlexaSiteStatsWidget" href="http://www.alexa.com/data/details/main?url=http://xxx">
<img alt="Alexa Certified Site Stats for xxx" src="http://xsltcache.alexa.com/site_stats/gif/t/a/eC1pbnZlc3QubmV0/s.gif" border="0">
</a>

I want to get target="_blank" in the < a > tag. This is what i tried already:

<script>document.getElementsByClassName("AlexaSiteStatsWidget").setAttribute('target', '_blank');</script>

<script>$('#AlexaSiteStatsWidget a').attr('target', '_blank');</script> 

But they both dont work.

Just change this:-

<script>document.getElementsByClassName("AlexaSiteStatsWidget").setAttribute("target","_blank");</script>

To this :-

<script>document.getElementsByClassName("AlexaSiteStatsWidget")[0].setAttribute("target","_blank");</script>

And remove this line :-

<script>$('#AlexaSiteStatsWidget a').attr('target', '_blank');</script> 

I don't know if it's gonna work but if you create an event listener on your <body>'s <a>s elements like this:

<script type="text/javascript">
 document.querySelector("body a.AlexaSiteStatsWidget").addEventListener("click", function() {
  this.setAttribute("target", "_blank");
 });
</script>

I didn't test it but i guess it gives you an idea of what i want to say

getElementsByClassName returns an array of all nodes (html elements) with the class name provided. If you only have one html element with the specified class, it will still return an array containing one node.

If you want to apply this to one <a> element use:

<script>
document.getElementsByClassName("AlexaSiteStatsWidget")[0].setAttribute('target', '_blank');
</script>

If want to apply this to multiple <a> elements:

<script>
var alexaArray = document.getElementsByClassName("AlexaSiteStatsWidget");

for(var i = 0; i < alexaArray.length; i++){
   alexaArray[i].setAttribute('target', '_blank');
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM