SitePoint Sponsor

User Tag List

Results 1 to 12 of 12

Hybrid View

  1. #1
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,746
    Mentioned
    45 Post(s)
    Tagged
    0 Thread(s)

    So I gotElementsByClass... Now What ?...

    I'm trying to apply a dynamic style to all elements on my page with a certain class.

    I'm using this getElementsByClassName function...


    Code JavaScript:
    function getElementsByClassName(className) 
    { 
      var arr = new Array(); 
      var elems = document.getElementsByTagName("*");
      for(var i = 0; i < elems.length; i++)
      {
    	 var elem = elems[i];
    	 var id = elem.getAttribute("id");
    	 var cls = elem.getAttribute("class");
    	 if(cls == className)
    	 {
    		arr[arr.length] = id;
    	 }
      }
      return arr;
    }

    And getting back an array of all the objects with that class, etc.

    Fine.

    So now what ?...

    I've been trying this...


    Code JavaScript:
    <script type="text/javascript">
    	bobArray = getElementsByClassName('Bob');
    	for( var i in bobArray )
    	{
    	(bobArray[i]).style.display = 'block';
    	}
    </script>

    The "for( var i in bobArray )" part is allegedly the Javascript equivalent of PHP's foreach loop, that loops through every record in an array, doing the same thing to each.

    So I'm trying to apply the style to each of the elements like that but getting back the ole "has no properties" error


    Quote Originally Posted by Firefox
    bobArray[i] has no properties
    Any ideas ?




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  2. #2
    SitePoint Addict
    Join Date
    Mar 2003
    Location
    In a house in the USA
    Posts
    293
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Daniel
    http://www.wlscripting.com - PHP Tutorials and code snippets
    Notepad++ Function List plugin tip - for PHP developers

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,629
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Is getElementsByClassName not already a DOM function? Try renaming the function?
    Ian Anderson
    www.siteguru.co.uk

  4. #4
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,746
    Mentioned
    45 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by WLHosting
    Have you looked at using jQuery?
    Thanks for the suggestion. But that'd be like using a bulldozer to build a sand-castle.

    Quote Originally Posted by siteguru
    Is getElementsByClassName not already a DOM function? Try renaming the function?
    It's not. I looked it up.

    And I even tried this usage and failed too...


    Code JavaScript:
    document.getElementsByClassName('SRSocialBookmarks').style.display = 'block';




    _
    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  5. #5
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by WLHosting
    Have you looked at using jQuery?
    This sort of response is starting to get annoying. jQuery may be the best thing since sliced bread, but it's not the solution to every single little problem, and some people might actually enjoy writing real javascript as opposed to using an abstraction of it. Besides, every man and his dog have heard of it, so it's no longer a useful response unless someone is really getting into convolutions and clearly could use a library/framework/whatever.

    Shaun, in your first example, are you sure the class is "Bob" and not "bob"?

    getElementsByClassName is a function available only to Firefox 3. So for compatibility's sake, you should do:

    Code Javascript:
    if (!document.getElementsByClassName) var getElementsByClassName = function(c, el) {
      if (!el) var el = document;
      var all = el.getElementsByTagName('*') els = [];
      for (var i = 0, j = all.length; i < j; i++) {
        if (all[i].className === c) els.push(all[i]);
      }
      return els
    }
    Note that this won't work for multiple class names:
    Code:
    <a href="#" class="item stuff">link</a>
    Other people have written very nice and bullet-proof functions that allow for this. If I remember correctly, Robert Nyman's I liked.

    Anyway, usage of the one I just typed up there:
    Code JavaScript:
    var stuff = getElementsByClassName('bob'); // referenced to document
     
    var bobdad = document.getElementById('bobdad');
    var stuff = getElementsByClassName('bob', bobdad);
     
    for (var i = 0, j = stuff.length; i < j; i++) {
      stuff[i].style.display = 'block';
    }

    The for...in loop is not the same as foreach. The forEach function (FF2+ and maybe others too) is more the same thing.

  6. #6
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,746
    Mentioned
    45 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the advice.

    I'll fiddle with this as soon as I can.




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  7. #7
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,746
    Mentioned
    45 Post(s)
    Tagged
    0 Thread(s)
    It worked !... I had to add a comma between the...

    var all = el.getElementsByTagName('*') els = [];
    var all = el.getElementsByTagName('*'), els = [];
    ...but that was the end of it.

    I double checked the first thing I was using and everything seemed correct. I don't know if there was a conflict with some other script I had on there. Or just that I was using the array wrong.

    Anyways, thanks a lot for your help, dude




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  8. #8
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ah, yes, small mistake there with the missing comma.

    Your original function, I've just noticed, was quite wrong. All it returns is an array of strings, those strings being the IDs of the elements that matched the given class name.
    Code javascript:
    var id = elem.getAttribute("id");
         var cls = elem.getAttribute("class");
         if(cls == className)
         {
            arr[arr.length] = id;
         }
    The variable id that you're putting in arr just contains the ID string, not the actual element. If you'd done this, they everything would have been gravy (though still a very verbose, inflexible and inefficient script):
    Code:
    arr[arr.length] = document.getElementById(id);
    for...in loops are really best used for object literals, e.g.:
    Code javascript:
    var a = {
      cat: 'mammal',
      salamander: 'amphibian',
      jellyfish: 'cnidarian'
    };
     
    for (var i in a) {
      alert('an example of a ' + a[i] + ' is a ' + i);
    }
    // outputs e.g. "an example of a mammal is a cat"
    Arrays, like most things in JavaScript, are objects (indexed with integers - 0, 1, etc.) so for...in works for arrays too but I try to stick to using for...in with object literals only.

  9. #9
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,746
    Mentioned
    45 Post(s)
    Tagged
    0 Thread(s)
    So it's something like a key/value pair ?

    The only thing I don't get is how that loop increments. Without assigning and increasing a counter variable, or without an array-pointer.




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse

  10. #10
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Yes, it's very much like that, like a hash-table. The loop must have an internal pointer, much like foreach in PHP.

  11. #11
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    The increments are performed internally. It's not a good idea to use for...in for arrays though, because for...in returns properties on them too, which you only want to happen when dealing with objects.

    The standard array iteration code stores the array length (to prevent multiple calls to the length property) and provides a variable with which to work with each array item.

    By declaring the loop index before the loop, you can use the same loop structure in many places. Declaring the index with the loop causes troubles when you try to use the same construct later on, so be sure to declare it outside of the loop.

    Code javascript:
    var elsLen = els.length,
        el,
        i;
    for (i = 0; i < elsLen; i += 1) {
        el = els[i];
        ...
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  12. #12
    Keep Moving Forward gold trophysilver trophybronze trophy
    Shaun(OfTheDead)'s Avatar
    Join Date
    Nov 2005
    Location
    Trinidad
    Posts
    3,746
    Mentioned
    45 Post(s)
    Tagged
    0 Thread(s)
    Psyche.

    That's very interesting. Thanks.

    I just know I'm going to forget it by the next time I'd need something like that though. haha

    I always find myself re-learning Javascript.




    Trying to fill the unforgiving minute
    with sixty seconds' worth of distance run.

    Update on Sitepoint's Migration to Discourse


Bookmarks

Posting Permissions

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