Is there a way to conditionally set an attribute using jQuery? For example, I want to simplify this:
$(element).val('99');
if ([condition]) {
$(element).attr('myAttr', 1);
}
This works, but forces me break the chaining of method calls. Instead, I would prefer something like this:
$(element).val('99').attr('myAttr', 1, [condition]);
So that the attribute is only set if the condition is true. How would I do this?
Well you could use:
$(element).val('99').attr('myAttr',[condition] ? 1 : $(element).attr('myAttr'));
Demo here
Option 2, just: $(element).val('99').attr('attr',[condition] ? 1 : undefined)
.
Demo here
Please notice that this option 2, as @FrédéricHamidi mentioned, might break the chain in older versions of jQuery. But works from jQuery 1.7.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With