Change all links by ClassName

Discussion in 'Web Design and Development' started by Me1000, Oct 19, 2008.

  1. Me1000 macrumors 68000

    Me1000

    Joined:
    Jul 15, 2006
    #1
    My javascript skills are amateur at best, but this is what im trying to do.

    I have code similar to this,
    Code:
    <a href="link.php" class="tempLinkForBadBrowsers"><div>lalala</div></a>
    <a href="link2.php" class="tempLinkForBadBrowsers"><div>lalala2</div></a>
    
    I would like to use javascript in order to change the links to:
    Code:
    href="#"
    
    for all links that have the class tempLinkForBadBrowsers

    and maybe add an "onclick" event to it, however at the moment that is being take care of with a div and isn't that important.

    After about an hour of googles' failed results i figured I would just ask real people! :)


    Thanks,
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    Here's a basic JavaScript function you can call to reset the href attribute all links with the same class name and also a spot for adding an event. Not sure what you were going to do with the event, so just made it do an alert.
    PHP:
    function RehrefLinks()
    {
      var 
    links document.getElementsByTagName('a');
      for (var 
    a=0b=links.lengthba++) {
        if (
    links[a].className == "tempLinkForBadBrowsers") {
          
    links[a].href "#";
          
    links[a].onclick = function() { alert('clicked'); };
        }
      }
    }
     
  3. Me1000 thread starter macrumors 68000

    Me1000

    Joined:
    Jul 15, 2006
    #3
    Thanks a million!

    That is exactly what I was looking for. :)
     
  4. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #4
    In recent browsers (Safari 3+, Firefox 3+, Opera 9.5 iirc) you can also use getElementsByClassName.
     

Share This Page