You confuse objects, elements and variables ...
These are HTML elements:
<div id="div1"></div> <div id="div2"></div>
JS objects play an important role in the language and look like this:
var object = {'bubu': 15, 'mama': 145, 'boo': 'kuku'} Элементы объектов достаются так: object.bubu; //Такая запись будет равна 15 object.mama; // = 145 object.boo; // = 'kuku'
And these are called "variables" (from the word variable):
var $d1 = $('#div1'), $d2 = $('#div2');
If it is necessary to perform the same action with several elements, it is more reasonable through a common class:
$('.bubu').on('click', function(){ $('.bubu').toggleClass('hidden'); });
.hidden {display: none;} .bubu {width: 100px; height: 100px; border: 2px solid orange; cursor: pointer; user-select: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="bubu" id="div1">booo</div> <div class="bubu hidden" id="div2">mooo</div>
But in your case it was possible to do with pure CSS:
.bubu, .kuku {width: 100px; height: 100px; border: 2px solid orange; cursor: pointer; user-select: none;} /* Изначально второй блок скрыт */ .kuku {display: none;} /* Все они находятся внутри label, поэтому любой клик переключает чекбокс */ /* А когда он включен - записываются другие стили */ .moo:checked ~ .kuku {display: block;} .moo:checked ~ .bubu {display: none;} /* Символ ~ означает "найти .bubu, который находится где-то ниже в коде от отмеченного чекбокса" */ /* Дописать .moo {display: none;} Чтобы скрыть чекбокс */
<label> <input type="checkbox" class="moo"> <div class="bubu" id="div1">booo</div> <div class="kuku" id="div2">mooo</div> </label>
There is also a general selector in CSS ... it works in JS: $("div[id^='div']")
- Such a thing will go through the whole page and find all the id of the div elements that start with the word "div". But it is rarely used, at least because then you can forget about it, and add more id on the page, starting with this word.