Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Should I use innerHTML to show a workshop name that must stay plain text?

Technology category photographTechnology

My practice page puts an entered workshop name into a label with innerHTML. The sample `Fold <b>paper</b>` appears with paper in bold. I wanted to show the brackets and letters exactly as entered, not accept formatting instructions.

MDN distinguishes textContent from HTML parsing and warns about using raw HTML for text. MDN's textContent reference

Would setting the label's textContent be the right fit? The surrounding card has its own buttons and layout, so I also want to make the change on the intended label without accidentally replacing the rest of the card.

Discussion

5 community replies

For a label that should contain plain text, textContent fits the requirement. InnerHTML interprets markup, which explains the bold word in your sample. Treat a name as text rather than asking an HTML parser to decide what parts should become page structure.

That distinction also matters for untrusted input. MDN warns that using innerHTML to set text can expose cross-site scripting risks. Don't turn this simple label into a place where someone else's supplied text is interpreted as HTML.

Apply the assignment to the dedicated label element. MDN notes that setting textContent removes the target node's existing children and replaces them with text. Setting it on the whole card could therefore remove buttons or other content you meant to keep.

If the card needs emphasis or icons, keep those in the structure you author and place the entered name in its own text area within that structure. You don't need to accept HTML in the name just because the surrounding design uses HTML.

Then try your bracketed sample alongside an ordinary name and one containing an ampersand. Confirm that the name is shown literally and that the card's controls remain. Both requirements belong to this small change.

Join the discussion

More in Technology