0

I hava a script that consist of "hello world" and the "hello" and "world" are in two different CSS styles.

I would like to click onto either of them and they would swap their styles. Example is I click on "hello" and it would swap style with "world". Below is my codes.

I couldn't get it to swap. How should I correct it ?

<html>
<head>
<style>
#today{
    font-weight: bold;
    color: red;
}

#normal{
    font-weight: normal;
    color: green;
}
</style>
<script>
    old="old";

        function set(in){
            var e = document.getElementsByName(old);
            for(ii=0;ii<e.length; ii++)
            {
                var obj = document.getElementsByName(old).item(ii);
                obj.id="normal";
            }
            old=in;
    var e = document.getElementsByName(old);
            for(ii=0;ii<e.length; ii++)
            {
                var obj = document.getElementsByName(old).item(ii);
                obj.id="today";
            }
        }
</script>
</head>
<body>
<table>
    <tr>
        <td id="normal" name="new" onclick="set('new')">Hello</td>
        <td id="today" name="old" onclick="set('old')">World</td>
    </tr>
</table>
</body>
</html>
1
  • I'm not sure that "name" is really a valid attribute for <td> elements. You can use non-standard attributes and they'll often or even usually work, but it's a little suspicious. Commented Oct 29, 2011 at 11:37

2 Answers 2

4

At any time, only one element can be annotated with an ID. Therefore, you should use classes instead of IDs to annotate your elements. Also, make sure to include a doctype.

Live demo of the corrected code:

<!DOCTYPE html>
<html>
<head>
<style>
.today{
    font-weight: bold;
    color: red;
}

.normal{
    font-weight: normal;
    color: green;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
  var els = document.querySelectorAll('.normal,.today');
  for (var i = 0;i < els.length;i++) {
    els[i].addEventListener('click', function () {
      var els = document.querySelectorAll('.normal,.today');
      for (var i = 0;i < els.length;i++) {
        var currentClass = els[i].getAttribute('class');
        var newClass = currentClass == 'today' ? 'normal' : 'today';
        els[i].setAttribute('class', newClass);
      }
    }, false);
  }
}, false);

</script>
</head>
<body>
<table>
    <tr>
        <td class="normal">Hello</td>
        <td class="today">World</td>
    </tr>
</table>
</body>
</html>

Of course, it's way easier to write with jQuery (demo):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
$(function() {
  $('.normal,.today').click(function() {
    $('.normal,.today').each(function(i, el) {
      var $el = $(el);
      if ($el.hasClass('today')) {
        $el.removeClass('today');
        $el.addClass('normal');
      } else {
        $el.removeClass('normal');
        $el.addClass('today');
      }
    });
  });
});
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

You usually want to put all the JavaScript code inside a immediately invoked function expression: (function () { /* all code here */ }); to enter a local scope and therefore prevent global namespace pollution...
@Šime Vidas Already did that in the jQuery version, added that in the regular JavaScript one too.
Thanks for the advance about using classes. It seems to be a more elegant approach via classes.
1

You have a few problems here. First, in your onclick handler, it has to be "javascript:set" instead of just "set". Second, you have a parameter named "in" which is a Javascript keyword. Change all references of it to "inv". If you do that, your code will sort-of work. Try it.

Beyond that, I suggest that you work in Firefox, and get the Firebug add-in, so that you can open the console. It will show you these kinds of errors.

1 Comment

However, to do what you're after, you shouldn't swap IDs. Instead you should work on swapping classes. IDs should be used to establish a permanent identity for a given DOM element. Swapping classes is a bit trickier in straight Javascript, but very easy if you use jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.