jake
jake

Reputation: 136

How to addClass or set multiple CSS properties to multiple elements which has variables?

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>

Upvotes: 0

Views: 86

Answers (3)

madalinivascu
madalinivascu

Reputation: 32354

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>

Upvotes: 3

Jon P
Jon P

Reputation: 19772

You could use an array and join:

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

$(arrSelectors.join).addClass("blue");

Upvotes: 0

Swapnil Patil
Swapnil Patil

Reputation: 942

$(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>

Upvotes: 0

Related Questions