Skip to content

Latest commit

Β 

History

History
73 lines (50 loc) Β· 2.34 KB

File metadata and controls

73 lines (50 loc) Β· 2.34 KB

prefer-dom-node-html-methods

πŸ“ Prefer .getHTML() and .setHTML() over .innerHTML.

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

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

Element#getHTML() and Element#setHTML() are safer and more modern alternatives to .innerHTML. Crucially, setHTML() automatically sanitizes the HTML to remove dangerous scripts before inserting it, while .innerHTML does not.

The rule checks reads from .innerHTML by default. Assignments are not checked by default because Safari does not support setHTML() yet. You can enable assignment checking with the checkSetHTML option.

Options

Type: object

checkGetHTML

Type: boolean
Default: true

Whether to check reads from .innerHTML.

checkSetHTML

Type: boolean
Default: false

Whether to check assignments to .innerHTML.

'unicorn/prefer-dom-node-html-methods': [
	'error',
	{
		checkSetHTML: true,
	},
]

Examples

// ❌ - No sanitization, vulnerable to XSS
const html = element.innerHTML;

// βœ… - No sanitization needed on read, but clearer API
const html = element.getHTML();
// ❌ - Dangerous! XSS vulnerability if html contains untrusted content
element.innerHTML = userProvidedHTML;

// βœ… - Automatically sanitizes malicious scripts
element.setHTML(userProvidedHTML);
// βœ… - Before setHTML(), you had to manually sanitize
// This was error-prone:
element.innerHTML = sanitizeHTML(userInput); // Easy to forget sanitization

// Now it's built in:
element.setHTML(userInput); // Automatic sanitization
// βœ… - Use trusted HTML when you know it's safe
element.setHTML('<strong>Safe static HTML</strong>');