max.dng max.dng - 4 years ago 104
HTML Question

How do I unselect items in jQuery?

I have a little problem with jQuery. I'm fairly new to it, so I'm going to explain what I'm doing in detail.
I have a couple h1's that get filled with consecutive numbers through jQuery.

<h1 class="number"><span></span></h1> *31

var date = 1;

$('.number').each(function() {
$(this).find('span').html(date);
date++;
});


I'm able to select individual
h1
's with
.addClass("selected")
.

$('.number').click(function() {
$(this).toggleClass("selected");
});


The problem is that I am able to select multiple elements. Ideally, I would be able to select one item and when I select a different one, the one before loses class "selected". How would I do that?

Answer Source

You can do it this way:

$('.number').click(function() {
  $(this).toggleClass("selected")
         .siblings('.selected').removeClass("selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>h1{margin:0;padding:.5em;font-size:16px;font-family:Arial,Helvetica,sans-serif;border-bottom:1px solid #ddd;cursor:pointer;-webkit-transition:all .15s ease;-moz-transition:all .15s ease;transition:all .15s ease}h1:hover{background:#eee}.selected{background: #555!important; color: #fff}.selected:hover{background: #666!important;}</style> <h1 class="number"><span>1</span></h1><h1 class="number"><span>2</span></h1><h1 class="number"><span>3</span></h1><h1 class="number"><span>4</span></h1><h1 class="number"><span>5</span></h1><h1 class="number"><span>6</span></h1><h1 class="number"><span>7</span></h1><h1 class="number"><span>8</span></h1><h1 class="number"><span>9</span></h1><h1 class="number"><span>10</span></h1><h1 class="number"><span>11</span></h1><h1 class="number"><span>12</span></h1><h1 class="number"><span>13</span></h1><h1 class="number"><span>14</span></h1><h1 class="number"><span>15</span></h1><h1 class="number"><span>16</span></h1><h1 class="number"><span>17</span></h1><h1 class="number"><span>18</span></h1><h1 class="number"><span>19</span></h1><h1 class="number"><span>20</span></h1><h1 class="number"><span>21</span></h1><h1 class="number"><span>22</span></h1><h1 class="number"><span>23</span></h1><h1 class="number"><span>24</span></h1><h1 class="number"><span>25</span></h1><h1 class="number"><span>26</span></h1><h1 class="number"><span>27</span></h1><h1 class="number"><span>28</span></h1><h1 class="number"><span>29</span></h1><h1 class="number"><span>30</span></h1><h1 class="number"><span>31</span></h1>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download