I have a string where part of the string depends on whether the variable json[i].has_dishwasher contains a value. If it contains a value, class="selected" will be added to the html string. To make my code shorter (I actually have a long series of the code shown below), i am planning to use the ternary if operator.
Problem: The way I used the ternary if conditional statement is not valid Javascript. How can I make this valid?
Javascript Code
html = '<div class="amenities"' + (json[i].has_dishwasher ? +'class="selected"'+) \
+ '>Dishwasher' + json[i].has_dishwasher + '</div>';
You need to add the “tri” part of the ternary, and it should return just the strings, not include the concatenation (
+) operators.But that isn’t really what you want either; that would leave you with two separate “class” attributes. I’d probably create the “class” attribute’s value apart from the creation of the HTML string:
Or just do it in a conditional and keep it clean.