Skip to content
Related Articles
Open in App
Not now

Related Articles

How to use conditional operator in jQuery a template?

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 23 Apr, 2021
Improve Article
Save Article
Like Article

In this article, we will learn to use ternary or conditional operator in jQuery.

The Ternary or Conditional operator takes three operands, a condition followed by question mark followed by two expressions to execute with a semicolon (:) in between the two expressions.


condition ? expression1 : expression2

Example: Now let us try an example to find how a conditional operator is used in the jQuery template.


    <script src=""></script>
<body style="text-align:center;">
   <h2 style="color:green">GeeksforGeeks</h2>
   <div style="background-color:red">
<p>Click the button to change the background color .</p>
       <button>Click me!</button>
    function toggleColor(){
      tag = $('div');
      // Ternary Operator (add/remove background color)
      // If tag color is green convert it to red otherwise convert to green.
     tag.css('background') == 'green' ? tag.css({'background':'red'}) : tag.css({'background':'green'});
    $('button').on('click', function(){


ternary operator

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!