Reputation: 3075
I am building an HTML element based on some JSON data. I would like to add a class to one element or the other based on a conditional variable, here's what I tried:
$(function() {
var lorem = true;
var html = '<div>' +
'<span class="ele ' + (lorem) ? 'green' : '' + '">Lorem</span>' +
'<span class="ele ' + (lorem) ? '' : 'green' + '">Ipsum</span>' +
'</div>';
$('.container').html(html);
});
.green {
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>
In this example I want class green
to be added to the first span
, but instead it appears to just be replacing the entire HTML with the word green
. I know that I could just set up the entire HTML variable within the conditional statement, but the HTML is going to end up being a lot of code so I would prefer not to do it that way if possible.
Upvotes: 0
Views: 159
Reputation: 3838
This is a common issue when building statements like this. Try to execute the following in the console:
'test' + (true) ? 'green' : ''
Your expectation is that this will end up being testgreen
. However this is not what logically is happening.
When the interpreter is running this code it first executes only the 'test' + (true)
part. The result of it is:
'test' + (true) => 'testtrue'
After that the rest of the statement is executed which right now is:
'testtrue' ? 'green' : ''
The testtrue
is always evaluated to true
so this is equivalent to calling true ? 'green' : ''
which ends up being just green
.
Upvotes: 0
Reputation: 771
You forgot parentheses, please see updated code.
I've also added a version with es6 multiline strings.
$(function() {
var lorem = true;
var html = '<div>' +
'<span class="ele ' + ((lorem) ? 'green' : '') + '">Lorem</span>' +
'<span class="ele ' + ((lorem) ? '' : 'green') + '">Ipsum</span>' +
'</div>';
var html2 = `<div>
<span class="ele ${lorem ? 'green' : ''}">Lorem2</span>
<span class="ele ${lorem ? '' : 'green'}">Ipsum2</span>
</div>`;
$('.container').html(html + '<br/>' + html2);
});
.green {
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>
Upvotes: 2
Reputation: 15847
If you wrap the ternary statement in parenthesis, it will do as you are looking.
$(function() {
var lorem = true;
var html = '<div>' +
'<span class="ele ' + ((lorem) ? 'green' : '') + '">Lorem</span>' +
'<span class="ele ' + ((lorem) ? '' : 'green') + '">Ipsum</span>' +
'</div>';
$('.container').html(html);
});
.green {
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>
Upvotes: 2