Skip to content

How to use JavaScript variable in HTML if condition | Example code

  • by

You can use if statement or ternary operator to use JavaScript variable in HTML. Ternary expressions will always return the first value if true, the second value if not.

var B = (A ==="red") ? "hot":"cool";

Great for one-off if/else statements, but if you get into more nested conditions, be sure to use the traditional if/else blocks for readability.

Use JavaScript variable in HTML if the condition

Simple example code.

<!DOCTYPE html>
    var color = "red";
    var B = (color ==="red") ? "hot":"cool";





How to use JavaScript variable in HTML if condition

Using if condition

Initialize your variables first, then compare using the if statement and assign new values where necessary.

    var color = "red";
    var b;

Do comment if you have any doubts or suggestions on this JS variable with the condition code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.