master_of_privates master_of_privates - 7 months ago 24
CSS Question

Id selector not working in jQuery

I feel like I'm missing something very basic here.

I basically have 2 divs in the markup. When you click one (#x), the other one (#block1) acquires a new class (.change), and changes its color.

The only problem is the selector ("#block1") inside the click function. If I replace the id of the first div with a class, it works fine. But using an id instead makes it invalid.



$(document).ready(function() {
$("#x").click(function() {
$("#block1").toggleClass("change");
});
});

#block1 {
width: 20vw;
height: 20vw;
background: gold;
margin-left: auto;
margin-right: auto;
position: relative;
}

#x {
height: 5vw;
width: 5vw;
background: #333;
position: relative;
right: -60vw;
top: -15vw;
cursor: pointer;
}

.change {
background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="block1"></div>
<div id="x"></div>




Answer Source

Your class, .change, won't override the background color set in #block1 due to style precedence.

In this particular instance you would have to be more specific.

Change this:

.change {
    background: red;
}

To this:

#block1.change {
    background: red;
}