I want to conditionally add an attribute using jQuery:
var $this = this
.append(...)
...
if (someCondition)
this.attr(...)
return $this;
That single silly conditional attribute addition breaks the beauty of my chain of jQuery method invocations. However, this could be overcome if .attr(someAttr, null) deleted the attibute someAttr:
return this
.append(...)
....
.attr(someAttr, someCondition ? someValue : null);
So the question is: Does .attr(someAttr, null) delete the attribute someAttr?
To remove an attribute using jquery, use .removeAttr.
According to this answer, as of 1.3 at least using null would actually cause the overloaded function to call just
.attr(attributeName), returning the current value.To set an empty value, use
.attr(attributeName, '')For conditional adding of an attribute, use