User97798 User97798 - 1 month ago 9
HTML Question

How toggle multiple element with one .toggle()

I know this question is kind of weird but i am not able to find out this

For Example : there is some div with ids

HTML

<div id="test1">test 1</div>
<div id="test2">test 2</div>
<div id="test3">test 3</div>
<div id="test4">test 4</div>
<div id="test5">test 5</div>
<div id="test6">test 6</div>


and i want to toggle some specific div
like

test1, test4 and test6


so i have to do like this

$('#test1').toggle();
$('#test4').toggle();
$('#test6').toggle();


but i want to know is there any way to do that like

$('#test1', '#test4', '#test6').toggle();


I know it can be done if i just give same class on the div which i want to toggle.

but i want to know this for that reason i asked

Answer

Sure you can, simply comma separate your ID selector:

$('#test1, #test4, #test6').toggle();

$("#toggle").on("click", function(){
  $('#test1, #test4, #test6').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE 1, 4, 6</button>

<div id="test1">test 1</div>
<div id="test2">test 2</div>
<div id="test3">test 3</div>
<div id="test4">test 4</div>
<div id="test5">test 5</div>
<div id="test6">test 6</div>

A much reusable code would allow you to toggle any desired elements without copy/pasting your JavaScript functions.
Here's an example where the desired selector to toggle is stored within the data-toggle attribute of the action element:

$("[data-toggle]").on("click", function(){
    $(this.dataset.toggle).toggle();
});
.hidden{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button data-toggle="#test1,#test6">Toggle 1, 6</button>
<button data-toggle="#test3,#test4">Toggle 3, 4</button>

<div id="test1">test 1</div>
<div id="test2">test 2</div>
<div id="test3">test 3</div>
<div id="test4">test 4</div>
<div id="test5">test 5</div>
<div id="test6">test 6</div>

<button data-toggle=".info">Toggle .info</button>
<p class="info hidden">This is some info</p>

Comments