Open In App

How to use conditional operator in jQuery a template?

Last Updated : 23 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Syntax:

condition ? expression1 : expression2

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

HTML




<!DOCTYPE HTML>
<html>
<head>
</head>
 
<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>
   </div>
 
  <script>
    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(){
      toggleColor();
    });
    </script>
</body>
</html>


Output:

ternary operator



Next Article

Similar Reads