Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to use conditional operator in jQuery a template?

Improve Article
Save Article
Like Article
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.

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
Last Updated : 23 Apr, 2021
Like Article
Save Article
Similar Reads