-
Notifications
You must be signed in to change notification settings - Fork 49
Working with HTML
Kyle Robinson Young edited this page Mar 26, 2016
·
2 revisions
The bel function returns a standard HTML Element.
Any HTML strings you include in the tagged template literal function call will be escaped.
var bel = require('bel')
var content = '<p>hi</p>'
var body = bel`<div>${content}</div>`
console.log(body)
// <div><p>hi</p></div>If you want to inject HTML unescaped, use Element.innerHTML:
var bel = require('bel')
var body = bel`<div></div>`
body.innerHTML = '<p>hi</p>'
console.log(body)
// <div><p>hi</p></div>If it needs to be embedded further down, create a placeholder element:
var content = bel`<p></p>`
content.innerHTML = '<strong>hi!</strong>'
var body = bel`<div>
<h3>heading</h3>
${content}
</div>`
console.log(body)
// <div><h3>heading</h3><p><strong>hi!</strong></p></div>Be careful when using innerHTML that no unescaped user supplied data makes it way in, as that will make your code susceptible to XSS attacks:
var userMessage = '<script>alert("whoops!")</script>'
var content = bel`<p></p>`
// Don't do this!
content.innerHTML = 'The user said: ' + userMessageInstead, make sure you escape any HTML in the userMessage before assigning to innerHTML:
var sanitizeHTML = require('sanitize-html')
content.innerHTML = 'The user said: ' + sanitizeHTML(userMessage)