1

I came across a curious problem when attempting to insert HTML edited by a Javascript editor (CKEditor) into some div. In the HTML to be inserted, double-quotes are replaced by the HTML entity " which works fine.

EXCEPT if the " appears in an inline style - then jQuery removes the entire inline sytyle.

I don't want them to be removed. I do prefer to keep the HTML entities if possible. The question is why does this happen? Any workaround?

In below example, I insert a text which should make the span red with regular quotes and with HTML-entity escaped quotes in an inline style.

The first line (div1) makes the span red, div2 is not red at all.

   window.onload = function() {
 $('#div1').html('<span style="color:red;">This text "here" is red</span>, while this is not.' );
 $('#div2').html('<span style=&quot;color:red;&quot;>This text &quot;here&quot; is red</span>, while this is not.' ); }

See JSFiddle/L7cq2pfd here

2
  • div2 style is not valid style=&quot;color:red;&quot; how do you get this style ? Commented Oct 18, 2015 at 8:52
  • CKEditor automatically does this, it adds inline styles when you edit. This is intended to help avoiding problems with texts containing quotes, but in this case it created a problem. Commented Oct 18, 2015 at 9:14

1 Answer 1

2

jQuery inserts this as style="&quot;color:red;&quot;" - convert &quot; to " with replace(/&quot;/g, '"') before inserting as HTML :

$('#div2').html('<span style=&quot;color:red;&quot;>This text &quot;here&quot; is red</span>, while this is not.'.replace(/&quot;/g, '"') ); 

http://jsfiddle.net/kb709s27/

Why? The automatically rendering of a &quot; to " is a browser feature, not a javascript feature. jQuery seems to parse the inserted HTML and tries to correct malformed attributes. If you insert

$('#div2').html('<span style=color:red>');

then jQuery corrects this and inserts <span style="color:red">. In your case jQuery only see a malformed attribute and therefore tries to correct it, wrapping &quot;color:red;&quot; into quotes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - this makes it clear and is what I needed. I was missing that the automatic HTML rendering is not a Javascript feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.