I am teaching myself jquery. I am trying for the first time to change elements of the dom using jquery. Particularly I am trying to use the method addClass to make a blue rectangle disappear. Here is the simple code:
html
<!DOCTYPE html>
<html>
<head>
<title>test slider</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<span id="rect"></span>
<p id="button"> click here </p>
</body>
</html>
css
#rect{
float: left;
height: 400px;
width: 550px;
background-color: blue;
}
.closed {
height: 0;
}
#button {
float: right;
margin-top: 200px;
margin-right: 500px;
}
jquery
$(document).ready(function(){
$("#button").click(function(){
$("#rect").addClass("closed");
});
});
I am expecting the rectangle to disappear when I click the text "click me", but nothing happens. I have checked with an alert box that everything else works.This is my first attempt so I expect it might be something pretty simple I am doing wrong. Any help appreciated.
That's because of the specificity of your CSS selectors. You're trying to override an ID with a class. Which won't work because an ID has a higher level of specificity than a class.
#= ID.= ClassThe main thing here is to change up the specificity of your selectors and I have outlined a few options below.
Change ID to Class
Change
#rectto.rect.Use a Different CSS Property
If you don't want to change up your ID then you you could have
.closedapply a property that#recthas not set, but would also hide the element likedisplay: none;.Increase CSS Selector Specificity
Per the comments below you could change one of your selectors to make it more specific.
Change
.closedto#rect.closed(no space between thetand.). This will target an element with an ID of#rectand a class of.closed.