Skip to content

Change target=“_blank” to target = “_self” for mobile

I’m trying this code:

if (window.matchMedia("(max-width: 767px)").matches) {
  // The viewport is less than 768 pixels wide 
  document.getElementById("link").target = "_self";
<a id="link" href="/something" target="_blank">Click Me</a>

But it’s working for only one id. I want to convert target="_blank" to target = "_self" for all the links in web page using one class or ID.

How do I do it?


The problem is that the ID is unique. That means you can only have one element with a specific ID. You can’t give this ID to another element. Therefore you should use your second approach: classes

In this code, you get all elements with the specific class and then set it’s targets to _self.

var tags = document.getElementsByClassName("className");
for(var i = 0; i < tags.length; i++) {
    tags[i].target = "_self";

HTML example:

<a class="className" href="/something" target="_blank">Click Me</a>