SitePoint Sponsor

User Tag List

Results 1 to 19 of 19

Thread: Using Classes

  1. #1
    Under Construction Poop_Shoot's Avatar
    Join Date
    Jul 2003
    Location
    Sacramento, CA
    Posts
    330
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using Classes

    Hey all, I know you can reference certain elements buy its ID many different ways! Is it possiblle to do the same with class names? I know I have seen javascript manipulating class names somewhere, .className or something? Thanxs 4 your time1

  2. #2
    SitePoint Member
    Join Date
    Aug 2003
    Location
    Netherlands
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There is no getelementsbyclassname function, but you could make it yourself quite easily:

    Code:
    <script type="text/javascript">
    function getclassname(arg){
    var temparray=new Array();
    var x=document.getElementsByTagName('*');
    xtemp=x.length;
    for (var i=0;i<xtemp;i++){
    if (x[i].className==arg){
    temparray.push(x[i]);
    };
    
    }
    return temparray;
    }
    document.getElementsByClassName=getclassname;
    alert(document.getElementsByClassName('test')[1].innerHTML);
    </script>

  3. #3
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, mw22 you beat me to the punch. Oh well, here's the post I was working on:

    Javascript uses the id attribute of the HTML element to access the Element object and it's properties, for example:
    Code:
    eleObj = document.getElementById(id);
    The id attribute of each element must be unique. A CSS class can be applied to more than one element, for example:
    Code:
    <style>
    .content {
      color:#000; background:#ccc;
    }
    </style>
    </head>
    <body>
    <div id='d1' class='content'>d1</div>
    <div id='d2' class='content'>d2</div>
    getElementById is the most direct way to get an object reference when you want a specific Element object corresponding to a unique id. Sometimes you need to get a list or array of all Element objects with something in common - for example all elements whose class attribute contains the string 'content'. The following provides that capability:
    Code:
    <html>
    <head>
    <style>
    #d1 {
      color:#000; background:#ccc; margin:1em;
    }
    #d2 {
      color:#ccc; background:#000; margin:2em;
    }
    .content {
      font-family:verdana,arial; text-size:14px;
    }
    </style>
    <script>
    window.onload = function() {
      var eleList = document.getElementsByClassName('content');
      var i, s = "Elements whose class attribute contains 'content':\n\n";
      for (i=0; i<eleList.length; ++i) {
        s += eleList[i].id + '\n\n';
      }  
      alert(s);
    }
    document.getElementsByClassName = function(clsName) {
      var i, elements, found, re;
      re = new RegExp("\\b"+clsName+"\\b");
      found = new Array();
      elements = document.all ? document.all : document.getElementsByTagName('*');
      for (i=0; i<elements.length; ++i) {
        if (elements[i].className.search(re) != -1) {
          found[found.length] = elements[i];
        }
      }
      return found;
    }
    </script>
    </head>
    <body>
    <div id='d1' class='content'>d1</div>
    <div id='d2' class='content'>d2</div>
    </body>
    </html>

  4. #4
    Under Construction Poop_Shoot's Avatar
    Join Date
    Jul 2003
    Location
    Sacramento, CA
    Posts
    330
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great Mike, You got a direct hit thats exactly Im lookin for! The whole thing makes sence but I dont understand what the

    re = new RegExp("\\b"+clsName+"\\b" );

    line does! I relly should learn more about regular expressions! Anyway Thanks again Mike and MW22! I cant thank you enough!

  5. #5
    Under Construction Poop_Shoot's Avatar
    Join Date
    Jul 2003
    Location
    Sacramento, CA
    Posts
    330
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I cant get over how awesome this script is! I can even return css style for every ID in a class

    Code:
    <html>
    <head>
    <style>
    #d1 {
      color:#000; background:#cccccc; margin:1em;
    }
    #d2 {
      color:#ccc; background:#000000; margin:2em;
    }
    .content {
      font-family:verdana,arial; text-size:14px;
    }
    </style>
    <script>
    function getClass(name) {
      var eleList = document.getElementsByClassName(name);
      var i, s = "";
      for (i=0; i<eleList.length; ++i) {
        s += eleList[i].currentStyle.backgroundColor + '\n\n';
      }
      if(s==""){
        s+="That is Not A Class Name In This Document!";
      }
      alert(s);
    }
    document.getElementsByClassName = function(clsName) {
      var i, elements, found, re;
      re = new RegExp("\\b"+clsName+"\\b" );
      found = new Array();
      elements = document.all ? document.all : document.getElementsByTagName('*');
      for (i=0; i<elements.length; ++i) {
        if (elements[i].className.search(re) != -1) {
          found[found.length] = elements[i];
        }
      }
      return found;
    }
    </script>
    </head>
    <body>
    <form>
    <input type="text" name="myClass">
    <input type="button" value="Do It" onclick="getClass(this.form.myClass.value)">
    <form>
    
    <div id='d1' class='content'>d1</div>
    <div id='d2' class='content'>d2</div>
    </body>
    </html>
    I'm literally Jumping for Joy! Thanxs Again!

    PS. Hey Mike did you write this one the fly!

  6. #6
    "Of" != "Have" bronze trophy Jeff Lange's Avatar
    Join Date
    Jan 2003
    Location
    Calgary, Canada
    Posts
    2,063
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The regex is because elements can have more than 1 class, a \b is a word break in PCRE.
    Who walks the stairs without a care
    It shoots so high in the sky.
    Bounce up and down just like a clown.
    Everyone knows its Slinky.

  7. #7
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Poop_Shoot,

    No, I didn't write that 'on the fly'. It was something I had lying around. Actually the original version may have come from Tim Scarfe - I can't really remember.

  8. #8
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Are the word boundary characters really needed for the search()?? You could just use indexOf() for this, no? Should be less expensive than a regex operation.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  9. #9
    SitePoint Member
    Join Date
    Aug 2003
    Location
    Netherlands
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, I did write it sort of on the fly. but I forgot that you could have multiple classes for the same element.
    Good catch Mike.
    Maybe this is something of interest for the topic starter also:
    http://simon.incutio.com/archive/200...entsBySelector

  10. #10
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yep, I think beetle's right. indexOf() seems to be a better choice there.

  11. #11
    Under Construction Poop_Shoot's Avatar
    Join Date
    Jul 2003
    Location
    Sacramento, CA
    Posts
    330
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That is quite an interesting link mw22! If only I understood how I could write scripts like that! Well Ill keep plugin away!

  12. #12
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well, I've thought about it some more and I know now why MikeFoster used the regex w/word boundaries

    .red { color: red }
    .redAndBig { color: red; font-size: 120% }

    Those will both trigger a find when looking for "red" with any other method.

    Well done Mike - you were right after all.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  13. #13
    ☆★☆★ silver trophy vgarcia's Avatar
    Join Date
    Jan 2002
    Location
    in transition
    Posts
    21,235
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    I hope nobody's writing their CSS classes like that!

  14. #14
    "Of" != "Have" bronze trophy Jeff Lange's Avatar
    Join Date
    Jan 2003
    Location
    Calgary, Canada
    Posts
    2,063
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I wrote something similar, however used match() instead of search() as match() just returns true or false.
    Who walks the stairs without a care
    It shoots so high in the sky.
    Bounce up and down just like a clown.
    Everyone knows its Slinky.

  15. #15
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    mw22, very interesting link - thanks!

    Thanks beetle - but I can't really remember if I wrote it. I may have modified it but I think Tim wrote the original.

    Poop_Shoot, yes I agree, it's a very useful function.

  16. #16
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jeff Lange
    I wrote something similar, however used match() instead of search() as match() just returns true or false.
    Actually, that couldn't be further from the truth.

    A quote from the guide
    Note <A id=1198153 name=1198153>If you execute a match simply to find true or false, use String.search or the regular expression test method.
    Additionally, more words about match() from MSDN
    If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the properties of the global RegExp object are updated to reflect the results of the match.
    The array returned by the match method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the last match.
    As you can see, the results of running match() are far more complicated than a simple boolean return.

    Did you have the two flip-flopped in your head?
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  17. #17
    ♪♪ ♪ ♪ ♪ ♪♪ ♪ ♪♪ Markdidj's Avatar
    Join Date
    Sep 2002
    Location
    Bournemouth, South UK
    Posts
    1,551
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Nice bit of work. Used the method to border divisions with a pic border instead of usual inset/outset etc.
    Code:
    function borderClass() {
    var x=document.getElementsByTagName('*');
    for(i=0;i<x.length;i++) {
    if(x[i].className.indexOf("border")>-1) {
    var h=x[i].style.width;var v=x[i].style.height
    x[i].innerHTML+='<img alt="UnitingRhythms" class="tlc" style="width:'+h+';height:20px" src="images/bamvsmlt.gif">'+
    '<img alt="UnitingRhythms" class="trc" style="width:20px;height:'+v+';" src="images/bamvsmlr.gif">'+
    '<img alt="UnitingRhythms" class="brc" style="width:'+h+';height:20px" src="images/bamvsmlb.gif">'+
    '<img alt="UnitingRhythms" class="blc" style="width:20px;height:'+v+';" src="images/bamvsmll.gif">'+
    '<img alt="UnitingRhythms" class="tlc" src="images/bamcsmltl.gif">'+
    '<img alt="UnitingRhythms" class="trc" src="images/bamcsmltr.gif">'+
    '<img alt="UnitingRhythms" class="brc" src="images/bamcsmlbr.gif">'+
    '<img alt="UnitingRhythms" class="blc" src="images/bamcsmlbl.gif">'
    }}}
    cheers....... been needing a bit of code like that.
    Last edited by Markdidj; Dec 21, 2004 at 07:29.
    LiveScript: Putting the "Live" Back into JavaScript
    if live output_as_javascript else output_as_html end if

  18. #18
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I had to use this for something and I made a few modifications:
    Code:
    /* xGetElementsByClassName()
       Returns an array of elements which are
       descendants of parentEle and have tagName and clsName.
       If parentEle is null or not present, document will be used.
       if tagName is null or not present, "*" will be used.
    */
      
    function xGetElementsByClassName(clsName, parentEle, tagName) {
    	var elements = null;
    	var found = new Array();
    	var re = new RegExp('\\b'+clsName+'\\b');
    	if (!parentEle) parentEle = document;
    	if (!tagName) tagName = '*';
    	if (parentEle.getElementsByTagName) {elements = parentEle.getElementsByTagName(tagName);}
    	else if (document.all) {elements = document.all.tags(tagName);}
    	if (elements) {
    		for (var i = 0; i < elements.length; ++i) {
    			if (elements[i].className.search(re) != -1) {
    				found[found.length] = elements[i];
    			}
    		}
    	}
    	return found;
    }

  19. #19
    "Of" != "Have" bronze trophy Jeff Lange's Avatar
    Join Date
    Jan 2003
    Location
    Calgary, Canada
    Posts
    2,063
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Did you have the two flip-flopped in your head?
    I think that's exactly what happened, lol. (Stupid memory)
    Who walks the stairs without a care
    It shoots so high in the sky.
    Bounce up and down just like a clown.
    Everyone knows its Slinky.


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
  •