Search code examples
jquerytoggleclass

toggleClass multiple divs


This code works when I only have one div and I use 'div' in jquery. It works on the <p>. It even works when I pinpoint with 'div:first-of-type'.

But when I use '#first' or '#second' the only thing that changes is the border. When I use 'div:last-of-type' everything changes but the background colour.

Why is the code not working properly???

<div id="first"></div>
<div id="second"></div>
<p>hello there</p>
<button>button</button>

<style>
div {
    width:200px;
    height:200px;
    background-color:midnightblue;
}

#second {
    background-color:darkgreen;
}

p {
    width:200px;
    height:20px;
    background-color:aqua;
}

button {
    width:50px;
    height:25px;
    background-color:brown;
    color:yellow;
}

.black {
    background-color:black;
    border:medium cornsilk dashed;
    width:100px;
    height:150px;
    color:aliceblue;
}
</style>

     <script>
     $(function() {
        $('button').click(function() {
            $('#second').toggleClass('black');
        }); 
     });
     </script>

Solution

  • See, IDs have more priority than the class name.

    #second {
        background-color:darkgreen;
    }
    

    this has the highest priority and:

    .black {
        background-color:black;
        border:medium cornsilk dashed;
        width:100px;
        height:150px;
        color:aliceblue;
    }
    

    has the least one yet the properties which are not in the id selector are applied but not the background-color.

    You can override it with #id.class:

     #second.black { /*  <------------------this way */
        background-color:black;
        border:medium cornsilk dashed;
        width:100px;
        height:150px;
        color:aliceblue;
    }
    

    You can hack it with !important (Not recommended though):

    .black {
        background-color:black !important;
        border:medium cornsilk dashed;
        width:100px;
        height:150px;
        color:aliceblue;
    }