Skip to content

Latest commit

Β 

History

History
56 lines (40 loc) Β· 2.12 KB

File metadata and controls

56 lines (40 loc) Β· 2.12 KB

prefer-toggle-attribute

πŸ“ Prefer using Element#toggleAttribute() to toggle attributes.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§πŸ’‘ This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Prefer using Element#toggleAttribute() instead of conditionally calling setAttribute() and removeAttribute() for boolean-style attributes.

Only setAttribute(name, '') patterns are autofixed. Non-empty static string values may get suggestions when safe.

data-* attributes are ignored so dom-node-dataset remains responsible for dataset-specific style.

Only direct hasAttribute() toggles are autofixed. Condition-driven toggleAttribute(name, force) replacements are suggestions when safe, because toggleAttribute(name, true) preserves existing non-empty values.

Optional receivers are fixed or suggested only for direct hasAttribute() toggles. Generic condition-driven optional receivers are reported without fixes because element?.toggleAttribute(name, condition) would skip evaluating condition when element is nullish.

Examples

// ❌
if (element.hasAttribute('hidden')) {
	element.removeAttribute('hidden');
} else {
	element.setAttribute('hidden', '');
}

// ❌
element.hasAttribute('hidden')
	? element.removeAttribute('hidden')
	: element.setAttribute('hidden', '');

// βœ…
element.toggleAttribute('hidden');
// ❌
if (condition) {
	element.setAttribute('hidden', '');
} else {
	element.removeAttribute('hidden');
}

// ❌
condition
	? element.setAttribute('hidden', '')
	: element.removeAttribute('hidden');

// βœ…
element.toggleAttribute('hidden', condition);