Coding with Jesse

target="_blank" With XHTML 1.1

January 24th, 2007

I received a question this morning from someone asking:

In XHTML 1.1 we cannot use attribute 'target=blank', so what is the solution?

The solution is to use regular links, but to make them open into a new window using JavaScript. To do this, we can add something to the links to flag them as being special, perhaps a class called new-window:

<a href="page.html" class="new-window">Page</a>

Then, use JavaScript to find all the links that have this class name and tell them to open in a new window:

window.onload = function() {
    var links = document.getElementsByTagName('a');
    for (var i=0;i < links.length;i++) {
        if (links[i].className == 'new-window') {
            links[i].onclick = function() {
                window.open(this.href);
                return false;
            };
        }
    }
};

or using jQuery:

$(function(){
    $('a.new-window').click(function(){
        window.open(this.href);
        return false;
    });
});

If you have any other questions like this, feel free to ask me and I'll be happy to answer them here.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!