JavaScript·100 questions

[ITEM 1] QUESTION: How to change the content of an element?

Answer

Changing the content of elements in the DOM is one of the most frequent tasks when developing interactive web applications. JavaScript provides several different properties for this purpose, each solving specific problems and having its own security and performance nuances.

The safest and most recommended way to manage text content is the textContent property. It sets or returns the text content of a node and all its descendants. When using textContent, all passed text is treated strictly as a string, not as HTML code. This means that if a user tries to inject a malicious script through an input field, the browser will simply display it as text rather than execute it. This approach completely protects the application from XSS (Cross-Site Scripting) attacks, so this property should always be preferred when working with plain text.

On the other hand, the innerHTML property allows not only changing text but also injecting full HTML markup. With its help, you can dynamically create complex structures inside an element by adding new tags, attributes, and nested blocks. However, the main problem with innerHTML is its vulnerability to XSS attacks. If you inject data obtained directly from users into innerHTML without prior strict sanitization, an attacker can execute arbitrary JavaScript code in the browser of other users. Therefore, innerHTML should only be used with fully trusted static or pre-sanitized content.

There is also the innerText property, which is largely similar to textContent, but takes into account CSS styles and the visibility of elements on the page. For example, innerText will not return the text of elements hidden using display: none and takes formatting into account. However, its use is more expensive for the browser in terms of performance, as it requires recalculating the page layout.

In real-world development, the choice boils down to a simple rule: use textContent for outputting plain text to ensure maximum security and speed, and use innerHTML for inserting pre-made markup after ensuring the data source is secure.

Was this answer helpful?

More questions in this topic

Related questions from other topics