Opening blog post links in new window with javascript - Can I adjust the module to ignore anchors?

New Contributor

Hi. At some point in time, the following custom module was created and applied to our current blog template to open all links within a post in a new tab:


window.onload = function() {
    const postbodylinks = document.getElementById('section-post-body').getElementsByTagName('a');
    for (var index = 0; index < postbodylinks.length; index++) {
            postbodylinks[index].setAttribute('target', '_blank');

My question: Is there something I can add to this bit of code that will make an exception for anchors? In our case, we're trying to implement a table of contents on some blog posts, but this module forces the anchors to open in a new tab, which we do not want.


Unfortunately, because my familiarity ends with CSS and HTML, I have no idea how this script works, as it doesn't look like other options for opening links in a new tab I can find online. The person who requested this module did so about a year ago, so the details of how it came into being have fallen into the murk.


If this is an acceptable question I would love an answer! I can share a link to a blog post with a table of contents if needed but I figured the issue/solution would be obvious to someone who knows Javascript. Thank-you in advance for any info you can offer.

1 Reply 1
Occasional Contributor

with that JQuery script you are targeting ALL links in the document and setting their attribute "target" to "_blank", I would suggest a different approach;
taking into account that you are working on a custom module, you could define a custom CSS class to be added just to links that you're intrested in, and then changing just their "target" attribute value.


 For reference (I suppose you would have to target "a"

child elements inside the container):

Hope that helps