0

How can I addClass or add css properties to multiple elements(id's) which has variables assigned to them. The code works if I use directly $('#cc, #dd').addClass('blue') but doesn't work if it has variables assigned to id's like $(cc, dd).addClass('blue'). Please check the below code, the commented line works but not if it has variables.

$(document).ready(function() {
    var cc = $("#cc"),
        dd = $("#dd");
    $("button").click(function() {
        // $("#cc, #dd").addClass("blue");
        $(cc, dd).addClass("blue");
        $(cc, dd).css({
            "color": "#2196f3",
            "font-size": "30px"
        });
        $("h1, h2, p").addClass("blue");
    });
});
.blue {
  color: #2196f3;
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
   
<div id="cc">hello 1</div>
<div id="dd">hello 2</div>

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>

<button>Add classes to elements</button>
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41
jake
  • 136
  • 1
  • 12

3 Answers3

3

Use add() to add the dd element to the cc collection, right now you are trying to find a cc element inside the dd element see selector context

var cc = $("#cc"),
    dd = $("#dd");
$(cc).add(dd).addClass("blue");
.blue {
  background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="cc"></button>
<button id="dd"></button>
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
0

$(document).ready(function() {
  var cc = $("#cc"),
      dd = $("#dd");
  $("button").click(function() {
      // $("#cc, #dd").addClass("blue");
      dd.addClass("blue");
      cc.addClass("blue");
      $(cc, dd).css({
          "color": "#2196f3",
          "font-size": "30px"
      });
      //$("h1, h2, p").addClass("blue");
  });
});
.blue {
    color: #2196f3;
    font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  
<div id="cc">hello 1</div>
<div id="dd">hello 2</div>

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>

<button>Add classes to elements</button>
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41
Swapnil Patil
  • 912
  • 1
  • 7
  • 14
0

You could use an array and join:

var arrSelectors = ["#cc", "#dd", ".someOtherSelector"];

$(arrSelectors.join).addClass("blue");
Jon P
  • 19,442
  • 8
  • 49
  • 72