Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

Am able to change the background of a div to blue with the below code using jquery.

$('#infoline').css('background-color', 'blue');


But not able to set it to to one of the bootstrap colors like the below code
$('#infoline').css('background-color', bg-primary);


Please advise the right way to do this.

What I have tried:

Tried even the below syntax :

$('#infoline').css('background-color', 'bg-primary');

and
$('#infoline').css('background-color', color.bg-primary);


Searched on google. Not able to get the right phrase for the relevant links.
Posted
Updated 29-Nov-20 20:08pm

1 solution

You need to play at class level for using bootstrap colors like:
JavaScript
$("p").addClass("bg-warning text-white");

More details: jQuery Get and Set CSS Classes[^]

A working sample:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").addClass("bg-warning text-white");
  });
});
</script>
</head>
<body>

<div class="container">
  <button>Set the color property of all p elements</button>
  <p>This is a paragraph.</p>
</div>

</body>
</html>
 
Share this answer
 
Comments
Priya-Kiko 30-Nov-20 2:12am    
Thank you. Got it !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900