'onClick change list styles

Let's say I have a simple list:

  <ul>
    <li class="notClicked">1</li>
    <li class="notClicked">2</li>
    <li class="notClicked">3</li>
  </ul>

Can I onClick of one "li" change styles of all li's except the one clicked?

So if I click "li" number 2, then the list will look like:

  <ul>
    <li class="notClicked">1</li>
    <li class="clicked">2</li>
    <li class="notClicked">3</li>
  </ul>

So if I click on first "li" then it will have clicked class, while others will be notClicked.

In case you want to play with it, here's jsbin: http://jsbin.com/ucuca4/edit

Make either in Prototype or plain JavaScript.



Solution 1:[1]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title></title>
        <script language="JavaScript" type="text/javascript">
            /*<![CDATA[*/
            var Lst;

            function CngClass(obj){
             if (Lst) Lst.className='';
             obj.className='Clicked';
             Lst=obj;
            }

            /*]]>*/
        </script>
        <style>
            .notClicked {color: black}
            .Clicked {color: red}
        </style>
    </head>

    <body>
        <ul>
            <li>
                <a onclick="CngClass(this);" href="#" class="notClicked">1
                </a>
            </li>
            <li>
                <a onclick="CngClass(this);" href="#"  class="notClicked">2
                </a>
            </li>
            <li>
                <a onclick="CngClass(this);" href="#"  class="notClicked">3
                </a>
            </li>
        </ul>
    </body>
</html>

Solution 2:[2]

Why change the style of the other? You may want to change the style of the clicked element.

If so, you can use jQuery for that

Example:

<li class = "notClicked">element 1</li>
<li class = "notClicked">element 2</li>
<li class = "notClicked">element 3</li>

$('.notClicked').click(function()
{
    $(this).addClass('active');
});

Solution 3:[3]

<script>
    function changeClass(){
        document.getElementById("idElement").setAttribute("class", "Clicked");
    }
</script>

<ul>
    <li class="notClicked" >1</li>
    <li class="notClicked" onClick="changeClass()" id="idElement">2</li>
    <li class="notClicked">3</li>
</ul>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen
Solution 3 Peter Mortensen