Array / getElementsByTagName(''); help

Discussion in 'JavaScript' started by sam., Jan 17, 2008.

  1. #1
    I have the following code which selects the anchor link in a div and makes the whole of any div with the class="homebox" clickable.

    window.onload = function(){
     var linkr = document.getElementsByTagName('div');
     for(var i=0,j=linkr.length;i<j;i++){
       if(linkr[i].className === 'homebox'){
        linkr[i].onclick = function(){
         window.location = this.getElementsByTagName('a')[0].href;
       }
      }
     }
    }
    Code (markup):
    I have a problem now though, as I have other elements that I need to use this code on (I need it to work for h2, div and li elements) but I can't get it to work.

    I am right in thinking that
     var linkr = document.getElementsByTagName('div');
    Code (markup):
    will only allow for one element, I am unable to array inside it like
     var linkr = document.getElementsByTagName('div','li','h2');
    Code (markup):
    A friend of mine said that best solution would probably be to add the tag I'm looking for as an argument in the function, then call it with whichever tag need need at any time (so if it's an li that clicked, it'll getElementsByTagName('li'); or if a div getElementsByTagName('div'); and so forth.

    Problem now is that I'm very new to JS, so could someone please help me out?!

    (I'd use CSS and a normal link but I am using text-image replacement so basically there is no content in the div it's all off screen and just a background image is used, hence me needing to use JS)
     
    sam., Jan 17, 2008 IP
  2. mjamesb

    mjamesb Member

    Messages:
    88
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    48
    #2
    Sample code...you don't really need to break it down this way but it shows you what is happening better....to any newbie trying JS you really should use FireFox and download FireBug which allows you to step through the code and see what is happening...not hard to use either.


    window.onload = MakeLinks()

    function MakeLinks()
    {
    var tags = ["div", "li", "h2"];
    findAllTagsToLink(tags);
    }
    function findAllTagsToLink(tags)
    {
    for (var i=0; i< tags.length; i++)
    {
    findTagType(tags;
    }
    }
    function findTagType(tag)
    {
    var myelements = document.getElementsByTagName(tag);
    for (var i=0; i < myelements.length; i++)
    {
    if (myelements.className === 'homebox')
    {
    //do whatever
    }
    }
    }
     
    mjamesb, Jan 18, 2008 IP