How to add target=”_blank” to a link within a specified div with JavaScript?

Sometimes, we want to add target=”_blank” to a link within a specified div with JavaScript.

In this article, we’ll look at how to add target=”_blank” to a link within a specified div with JavaScript.

How to add target=”_blank” to a link within a specified div with JavaScript?

To add target=”_blank” to a link within a specified div with JavaScript, we use querySelectorAll.

For instance, we write

const linkList = document.querySelectorAll("#link_other a");

for (const link of linkList) {
  link.setAttribute("target", "_blank");
}

to call querySelectorAll to select all the links inside the element with ID link_other.

Then we use a for-of loop to loop through each link.

In it, we call setAttribute to set the 'target' to '_blank'.

Conclusion

To add target=”_blank” to a link within a specified div with JavaScript, we use querySelectorAll.