Changing an elements CSS class style with DHTML

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bissatch@yahoo.co.uk

    Changing an elements CSS class style with DHTML

    Hi,

    Is it possible to change the class style of an HTML element using
    DHTML? For example...

    <td class="my_class ">Text</td>

    I have used DHTML to change style elements such as backgroundColor so I
    assume that it can be used to change the class too.

    Cheers

    Burnsy

  • phil_gg04@treefic.com

    #2
    Re: Changing an elements CSS class style with DHTML

    > Is it possible to change the class style of an HTML element using[color=blue]
    > DHTML? For example...
    > <td class="my_class ">Text</td>[/color]

    Easy, just change the className property of the element:
    <td id="foo" class="a">
    document.getEle mentById("foo") .className="b";

    Here are a couple of general-purpose functions that I use to add and
    remove classes:

    function has_class(e,c) {
    var cn=" "+e.classNa me+" ";
    return cn.indexOf(" "+c+" ")!=-1;
    }

    function add_class(e,c) {
    if (!has_class(e,c )) {
    e.className=e.c lassName+" "+c;
    }
    }

    function remove_class(e, c) {
    var cn=e.className;
    var p=cn.indexOf(c) ;
    if (p==-1) return;
    cn=cn.substr(0, p)+cn.substr(p+ c.length);
    e.className=cn;
    }


    Note: in your example, you used an _ in the class name. Although this
    is now allowed some previous versions of the CSS spec did not allow _
    in class names, so for maximum cross-browser compatibility you should
    avoid it. Use - instead.

    --Phil.

    Comment

    • RobG

      #3
      Re: Changing an elements CSS class style with DHTML

      bissatch@yahoo. co.uk wrote:[color=blue]
      > Hi,
      >
      > Is it possible to change the class style of an HTML element using
      > DHTML? For example...
      >
      > <td class="my_class ">Text</td>
      >
      > I have used DHTML to change style elements such as backgroundColor so I
      > assume that it can be used to change the class too.
      >
      > Cheers
      >
      > Burnsy
      >[/color]

      If you just want to change the class:

      <style type="text/css">
      .classA {background-color: red;}
      .classb {background-color: blue;}
      </style>
      <div style="width: 100px; height: 100xp;"
      class="classA"
      onmouseover="th is.className='c lassB';"
      onmouseout="thi s.className='cl assA';"[color=blue]
      >blah</div>[/color]


      But if you want to change the actual style rule, that's a different
      matter (but not impossible).


      --
      Rob

      Comment

      • FredOz

        #4
        Re: Changing an elements CSS class style with DHTML

        phil_gg04@treef ic.com wrote:[color=blue][color=green]
        >>Is it possible to change the class style of an HTML element using
        >>DHTML? For example...
        >><td class="my_class ">Text</td>[/color]
        >
        >
        > Easy, just change the className property of the element:
        > <td id="foo" class="a">
        > document.getEle mentById("foo") .className="b";
        >
        > Here are a couple of general-purpose functions that I use to add and
        > remove classes:
        >
        > function has_class(e,c) {
        > var cn=" "+e.classNa me+" ";
        > return cn.indexOf(" "+c+" ")!=-1;
        > }[/color]

        Try these:

        function has_class(e,c) {
        var re = new RegExp('\\b'+c+ '\\b');
        return (re.test(e.clas sName));
        }
        [color=blue]
        >
        > function add_class(e,c) {
        > if (!has_class(e,c )) {
        > e.className=e.c lassName+" "+c;
        > }
        > }[/color]

        function add_class(e,c) {
        if (!has_class(e,c )) {
        e.className += " " + c;
        }
        }
        [color=blue]
        >
        > function remove_class(e, c) {
        > var cn=e.className;
        > var p=cn.indexOf(c) ;
        > if (p==-1) return;
        > cn=cn.substr(0, p)+cn.substr(p+ c.length);
        > e.className=cn;
        > }[/color]

        function remove_class(e, c) {
        var re = new RegExp ('\\b'+c+'\\b') ;
        e.className = e.className.rep lace(re,'');
        }



        --
        Fred

        Comment

        • phil_gg04@treefic.com

          #5
          Re: Changing an elements CSS class style with DHTML

          > e.className += " " + c;

          Yes, that does save a few microseconds of download time. But I
          generally try to avoid += after a nasty incident where it did an
          increment rather than a string append and I spent ages debugging it. I
          now use "-=-" for increment, or write it out long-hand.

          As for the regexps, you might save some more microseconds of execution
          time by keeping them around from one invocation to the next:

          var removeclass_re = new RegExp ('\\b'+c+'\\b') ;
          function remove_class(e, c) {
          e.className = e.className.rep lace(removeclas s_re,'');
          }

          I don't know if browsers actually spend any significant time compiling
          regular expressions, but this would certainly be the "right way" to do
          it in other languages.

          Comment

          • Thomas 'PointedEars' Lahn

            #6
            Re: Changing an elements CSS class style with DHTML

            <phil_gg04@tree fic.com> wrote [...]:

            This is Usenet, please provide proper attribution.
            vvvvvvvvvvvvvvv vvvvvvvvvvvv[color=blue][color=green]
            > > e.className += " " + c;[/color]
            >
            > Yes, that does save a few microseconds of download time. But I
            > generally try to avoid += after a nasty incident where it did an
            > increment rather than a string append[/color]

            This could have happened only because you were (are?) not aware of property
            types and automatic type conversion. Whenever a string operand is involved,
            the other operand of `+=' is converted to string and so concatenation is
            performed rather than addition.
            [color=blue]
            > and I spent ages debugging it. I now use "-=-" for increment,[/color]

            You use a syntax error to achieve anything? I sincerely doubt that.
            [color=blue]
            > or write it out long-hand.[/color]

            That would be better, indeed.
            [color=blue]
            > [...]
            > I don't know if browsers actually spend any significant time compiling
            > regular expressions, [...][/color]

            They do.


            PointedEars

            Comment

            • phil_gg04@treefic.com

              #7
              Re: Changing an elements CSS class style with DHTML

              I wrote:[color=blue][color=green]
              >> I generally try to avoid += after a nasty incident where it did an
              >> increment rather than a string append[/color][/color]

              And Thomas 'Pointed Ears' Lahn replied:[color=blue]
              > Whenever a string operand is involved,
              > the other operand of `+=' is converted to string and so concatenation[/color]
              is[color=blue]
              > performed rather than addition.[/color]

              The problems and potential bugs come when you have something that you
              think is a string, but it happens to contain only digits and so is a
              number: e.g. phone numbers, credit card numbers and so on. (Have you
              ever seem a program or web site strip leading zeros from a phone
              number? Or suffer an integer overflow when you enter 20 digits?). Or,
              vice-versa, you think you have a number but actually have a string;
              this could easily happen if you have parsed a number out of a string
              with a regexp, for example, and it's difficult to debug because
              'alert(x)' will give no clue.

              The incident that I mentioned before was a long time ago and I forget
              the details, but it was to do with parsing CSS length units, i.e.
              splitting something like "10px" into a number (10) and a unit (px);
              instead of adding 1 to the length (11px) I ended up appending 1
              (101px).
              [color=blue][color=green]
              >> I now use "-=-" for increment[/color]
              > syntax error[/color]

              Try this:

              function test(a) {
              var b=a; var c=a;
              b+=1;
              c-=-1;
              if (b==c)
              alert ("passed for "+a+": += and -=- both yield "+b);
              else
              alert ("failed for "+a+": += yields "+b+" while -=- yeilds "+c);
              }

              function main() {
              test(1);
              test(-1);
              test(1000);
              test("10");
              }


              You'll see that += and -=- have the same behaviour when their operands
              are numbers. When one or other is actually a string, += does a string
              append while -=- converts them to numbers first.


              --Phil.

              Comment

              • Lasse Reichstein Nielsen

                #8
                Re: Changing an elements CSS class style with DHTML

                phil_gg04@treef ic.com writes:

                [color=blue]
                > The problems and potential bugs come when you have something that you
                > think is a string, but it happens to contain only digits and so is a
                > number:[/color]

                A string containing only digits is still a string. The problem comes
                when the programmer forgets what type the value is. It's a problem,
                but it's not like the language changes strings to numbers without
                telling you.
                [color=blue]
                > e.g. phone numbers, credit card numbers and so on. (Have you
                > ever seem a program or web site strip leading zeros from a phone
                > number? Or suffer an integer overflow when you enter 20 digits?).[/color]

                That's because it's parsing the string into a number. It calls for
                input validation, just as any other handling of user input, but
                the type is not the problem.
                [color=blue]
                > Or, vice-versa, you think you have a number but actually have a
                > string; this could easily happen if you have parsed a number out of
                > a string with a regexp, for example, and it's difficult to debug
                > because 'alert(x)' will give no clue.[/color]

                Yep, if the programmer can't keep track of the types of his values,
                Javascript is permissive enough to let him hang himself :).
                It's one of the advantages of statically typed languages, that they
                safeguard you from yourself.
                [color=blue]
                > The incident that I mentioned before was a long time ago and I forget
                > the details, but it was to do with parsing CSS length units, i.e.
                > splitting something like "10px" into a number (10) and a unit (px);
                > instead of adding 1 to the length (11px) I ended up appending 1
                > (101px).[/color]

                A classic :).
                [color=blue][color=green][color=darkred]
                >>> I now use "-=-" for increment[/color][/color][/color]

                Cute!
                /L
                --
                Lasse Reichstein Nielsen - lrn@hotpop.com
                DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                'Faith without judgement merely degrades the spirit divine.'

                Comment

                • Thomas 'PointedEars' Lahn

                  #9
                  Re: Changing an elements CSS class style with DHTML

                  <phil_gg04@tree fic.com> wrote [...]:[color=blue]
                  > I wrote:[color=green][color=darkred]
                  > >> I generally try to avoid += after a nasty incident where it did an
                  > >> increment rather than a string append[/color][/color]
                  >
                  > And Thomas 'Pointed Ears' Lahn replied:[/color]

                  You almost got it.

                  1. Who is `I' in a cited *public* discussion?
                  2. The basics of accepted attribution are described in the newsgroup's
                  FAQ notes. I strongly suggest you read those (more) thoroughly.
                  [color=blue][color=green]
                  > > Whenever a string operand is involved,
                  > > the other operand of `+=' is converted to string and so concatenation[/color]
                  > is[/color]
                  ^^^^[color=blue][color=green]
                  > > performed rather than addition.[/color][/color]

                  Posting borken quotes subsequently corrected in the view of Google Groups
                  users are a major malfunction of the Google Groups Web interface. I
                  strongly suggest that either you perform manual reformatting so that quoted
                  lines do not exceed 72 characters per line, or stop using Google Groups for
                  posting and start using a newsreader application instead. GG ist still good
                  for research, though.
                  [color=blue]
                  > The problems and potential bugs come when you have something that you
                  > think is a string, but it happens to contain only digits and so is a
                  > number: e.g. phone numbers, credit card numbers and so on. (Have you
                  > ever seem a program or web site strip leading zeros from a phone
                  > number?[/color]

                  No, and such applications would be borken. Leading zeroes in phone numbers
                  indicate that the participant is located outside the current city (0) or
                  country code (00) area and thus must not be stripped automatically; this
                  requires the phone number to be stored (in the database) and processed (as
                  variable value) as a character string .
                  [color=blue]
                  > Or suffer an integer overflow when you enter 20 digits?).[/color]

                  What's your point? A 20-digit number where leading zeroes are allowed to be
                  stripped is pretty well covered by a 64 bit floating-point number
                  representation (but it is likely to be rounded) as used in JavaScript 1.0
                  and ECMAScript implementations . Other languages also introduce appropriate
                  long integer types. Unless the application has been improperly designed,
                  there is no reason for an integer overflow here.
                  [color=blue]
                  > Or, vice-versa, you think you have a number but actually have a string;
                  > this could easily happen if you have parsed a number out of a string
                  > with a regexp, for example, and it's difficult to debug because
                  > 'alert(x)' will give no clue.[/color]

                  alert([x, typeof x, x.length]);

                  certainly will.
                  [color=blue]
                  > The incident that I mentioned before was a long time ago and I forget
                  > the details, but it was to do with parsing CSS length units, i.e.
                  > splitting something like "10px" into a number (10) and a unit (px);
                  > instead of adding 1 to the length (11px) I ended up appending 1
                  > (101px).[/color]

                  See the *real* problem?
                  [color=blue][color=green][color=darkred]
                  > >> I now use "-=-" for increment[/color]
                  > > syntax error[/color]
                  >
                  > Try this:
                  > [...]
                  > c-=-1;
                  > [...]
                  > You'll see that += and -=- have the same behaviour when their operands
                  > are numbers. When one or other is actually a string, += does a string
                  > append while -=- converts them to numbers first.[/color]

                  Now I see it, you use the `-=' operator (not `-=-') and a previously omitted
                  negative number as operand. That can become useful, although it alone is
                  less efficient than simple `+='.


                  PointedEars

                  Comment

                  • Randy Webb

                    #10
                    Re: Changing an elements CSS class style with DHTML

                    Thomas 'PointedEars' Lahn wrote:[color=blue]
                    > <phil_gg04@tree fic.com> wrote [...]:
                    >[color=green]
                    >>I wrote:
                    >>[color=darkred]
                    >>>>I generally try to avoid += after a nasty incident where it did an
                    >>>>increment rather than a string append[/color]
                    >>
                    >>And Thomas 'Pointed Ears' Lahn replied:[/color]
                    >
                    >
                    > You almost got it.
                    >
                    > 1. Who is `I' in a cited *public* discussion?[/color]

                    Are you actually so anally retentive that a person writing "I" does not
                    seem to you to be pointing at the person who wrote it?



                    --
                    Randy
                    comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
                    Answer:It destroys the order of the conversation
                    Question: Why?
                    Answer: Top-Posting.
                    Question: Whats the most annoying thing on Usenet?

                    Comment

                    Working...