Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to use conditional operator in jQuery a template?

  • Difficulty Level : Medium
  • Last Updated : 23 Apr, 2021

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>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</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

My Personal Notes arrow_drop_up

Start Your Coding Journey Now!