Reputation: 430
i need to do a shorthand IF-ELSE with JQuery. My code:
$('#somediv').val() != 0 ? $('#somediv').toggleClass('class1') : $('#somediv').toggleClass('class2');
Simple code, but doesn't work. Some help please? Thanks in advance
EDIT: this work:
if ($('#somediv').val() != 0) {
$('#somediv').toggleClass('class1');
}else{
$('#somediv').toggleClass('class2');
}
But the shorthand doesn't...Ty for the patience
Upvotes: 2
Views: 2396
Reputation: 1656
You want to use text() to get the value of the div, that's if it's not an input. If you provide what #somediv
looks like that will help.
$('#somediv').text() != 0 ? $('#somediv').toggleClass('class1') : $('#somediv').toggleClass('class2');
The shorthand "if-else" is called ternary and can be used with vanilla javascript
Upvotes: 0
Reputation: 68400
If somediv
is actually a div as the name would indicates, you should use text()
or html()
instead of val()
since value is only valid for input elements.
Upvotes: 3