I have a contentEditable
div within which I need to allow the user to edit HTML.
Do I need to sanitize the HTML the user writes inside that div?
I mean when I retrieve the HTML from that div, it's already sanitized. For example, if I wrote something like <>
inside the div, and then retrieved that back, I'd get <>
.
Test it here: http://jsfiddle.net/mByWT/
My other question is: is this behavior a standard, and can I rely on it across all browsers?
EDIT
I can now conclude that this is a general pattern:
element.innerHTML
returns escaped HTML -- it escapes <
, >
amd &
but not quoteselement.innerText
and element.textContent
return the literal HTML without escapingSee this: http://jsfiddle.net/2CmjG/
To edit the content in HTML, we will use contenteditable attribute. The contenteditable is used to specify whether the element's content is editable by the user or not. This attribute has two values. true: If the value of the contenteditable attribute is set to true then the element is editable.
contenteditable is an HTML attribute that you can add to any HTML element. If its value is true or an empty string, that means that the user can edit it by clicking the element. For example: <div contenteditable="true"> Change me! </ div>
Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
set contenteditable to false and it should work !! that simple. use contenteditable attribute for div to make it editable or not and use readonly attr for form input elements. Save this answer.
I think that you answered yourself :). Fact that innerHTML
of contenteditable div returns encoded HTML is a general pattern. Otherwise typing <
or >
or
or other HTML special entities would break this editor.
However, I'm pretty sure that there're edge cases for which browsers will produce different results and data created on e.g. IE won't be valid on Fx. But I've never observed anything critical. You also won't be able to encode data given by innerHTML
, because that would be very tricky.
jQuery is build to be compatible with all browsers, if you used your code in all browsers, it would preform the same way.
You would want to sanitize your HTML, however, because characters like <
and >
can confuse javascript. You want to sanitize HTML even more so if it's going to a database, or something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With