javascriptcssclassnew-window

Get an element by class and make it open in a new tab


I got some links in my HTML built by a WordPress shortcode. Unfortunately this shortcode do not include the target property and this way I cannot make the links open in a new tab.

I am not a programmer and I'm looking for a little JS to make some links under a specific class open in a new tab.

Something like:

if ("a" tag is under "div.newTab" class) onClick {window.open in a new tab}

Hope you guys understand it!

Thank you all.


Solution

  • window.onload = function(){
        var allLinks = document.querySelectorAll("div.newTab a");
        for(var i = 0; i < allLinks.length; i++){
            var currentLink = allLinks[i];
            currentLink.setAttribute("target", "_blank");
        }
    }