Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML inside contenteditable div

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 &lt;&gt;.

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 quotes
  • element.innerText and element.textContent return the literal HTML without escaping

See this: http://jsfiddle.net/2CmjG/

like image 795
treecoder Avatar asked Jul 04 '12 05:07

treecoder


People also ask

How do you use Contenteditable in HTML?

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.

What is Contenteditable div?

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>

How do you make a div Contenteditable?

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.

How do I turn off Contenteditable div?

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.


2 Answers

I think that you answered yourself :). Fact that innerHTML of contenteditable div returns encoded HTML is a general pattern. Otherwise typing < or > or &nbsp; 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.

like image 175
Reinmar Avatar answered Sep 28 '22 09:09

Reinmar


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.

like image 23
Polyov Avatar answered Sep 28 '22 10:09

Polyov