jquery / jquery

jQuery JavaScript Library
https://jquery.com
MIT License
58.93k stars 20.62k forks source link

Attributes: Make `.attr( name, false )` remove for all non-ARIA attrs #5452

Closed mgol closed 1 month ago

mgol commented 2 months ago

Summary

The HTML spec defines boolean attributes: https://html.spec.whatwg.org/#boolean-attributes that often correlate with boolean properties. If the attribute is missing, it correlates with the false property value, if it's present - the true property value. The only valid values are an empty string or the attribute name.

jQuery tried to be helpful here and treated boolean attributes in a special way in the .attr() API:

  1. For the getter, as long as the attribute was present, it was returning the attribute name lowercased, ignoring the value.
  2. For the setter, it was removing the attribute when false was passed; otherwise, it was ignoring the passed value and set the attribute - interestingly, in jQuery >=3 not lowercased anymore.

The problem is the spec occasionally converts boolean attributes into ones with additional attribute values with special behavior - one such example is the new "until-found" value for the hidden attribute. Our setter normalization means passing those values is impossible with jQuery. Also, new boolean attributes are introduced occasionally and jQuery cannot easily add them to the list without incurring breaking changes.

This patch removes any special handling of boolean attributes - the getter returns the value as-is and the setter sets the provided value.

To provide better backwards compatibility with the very frequent false value provided to remove the attribute, this patch makes false trigger attribute removal for ALL non-ARIA attributes. ARIA attributes are exempt from the rule since many of them recognize "false" as a valid value with semantics different than the attribute missing. To remove an ARIA attribute, use .removeAttr() or pass null as the value to .attr() which doesn't have this exception.

Fixes gh-5388

Richard Gibson is added as a co-author.

Checklist

mgol commented 2 months ago

Size differences:

main @f80e78ef3e7ded1fc693465d02dfb07510ded0ab
   raw     gz Filename
  -273   -109 dist/jquery.min.js
  -273   -102 dist/jquery.slim.min.js
  -273   -104 dist-module/jquery.module.min.js
  -273   -100 dist-module/jquery.slim.module.min.js
mgol commented 2 months ago

Issues created: