π 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.
Type: object
Type: boolean
Default: true
Whether to check reads from .innerHTML.
Type: boolean
Default: false
Whether to check assignments to .innerHTML.
'unicorn/prefer-dom-node-html-methods': [
'error',
{
checkSetHTML: true,
},
]// β - 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>');