Results 1 to 2 of 2

Thread: JS to set a target _Blank on an href with no ID or Class

  1. #1
    Join Date
    Dec 2007

    JS to set a target _Blank on an href with no ID or Class

    Hello Guys,

    I am working on coding a Javascript that will watch for a click event on an href that does not have an id or class. The links are generated automatically and I can't add an ID or Class to them. I need the script to watch for the click event and use a target = "_Blank" to open a new window.

    Any help would be appreciated.

    This is what I have so far but doesn't work.

    Here my code


    <a href="http://test.com/resources/blog/">Blog</a>


    document.addEventListener("click", function (e) {

    if (e.event.target.href == "http://test.com/resources/blog/" && !e.target.hasAttribute("target")) {
    e.target.setAttribute("target", "_blank");

  2. #2
    Join Date
    Mar 2005
    Behind you...
    The first thing that appears to be wrong is you checking '.target.href' on 'e.event'. All references to the object clicked should just be 'e.target' (as e is the event).

    Once that small thing is corrected your code appears to work.
    document.addEventListener("click", function(e) {
    	if(e.target.href == "http://test.com/resources/blog/" && !e.target.hasAttribute("target")) e.target.setAttribute("target", "_blank");
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center

Recent Articles