Tharindu Gallage Tharindu Gallage - 27 days ago 11
HTML Question

Javascript- do somthing onclick any <a> tag except href="#" and href="<javascript>" tags

How to do something

onclick
any
<a>
tag except
href="#"
and
href="javascript"
tags

I have a script but it also working on
href="#"
like tags. I want to exclude
href="#"
and
href="javascript"
tags.

this is my current script



window.addEventListener('load', function (){
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if(anchor.getAttribute("href"))
anchor.target = "_blank";
}

function tabunder() {
window.location = 'https://example.com' ;
}


for (var i=0; i<anchors.length; i++){
anchors[i].onclick = tabunder;
}


});




Answer

Try to add if statement like below:

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
  var anchor = anchors[i], t = anchor.getAttribute("href");
  if (t){
    if(t === "#" || t === ""){continue;}
    anchor.target = "_blank";
  }
}
Comments