Skip to content Skip to sidebar Skip to footer

Dynamically Changing The Html Of A Div With Jquery Is Causing Html Encoding To Be Lost

I have a piece of code which dynamically alters the HTML of a div called 'accordion' on the fly like so: // htmlstring contains some HTML containing some HTML encoding // e.g. <

Solution 1:

When the HTML code is merged into the DOM, everything is canonicalized into the internal DOM representation, the original HTML coding is irrelevant. Apostrophe and &#39; are equivalent in HTML code, so they turn into the same thing in the DOM.

What you need to do is escape the inner apostrophe. htmlstring should contain:

<spanclass='clickableComponent component'onclick="ComponentClicked('4612', 'Don\'t know', '44761');">Don't know</span>

Issues like this are one of the reasons why inline Javascript in HTML elements is not recommended. It would be cleaner if you did something like:

$(".clickableComponent").click(function() {
    ComponentClicked('4612', "Don't know", '44761');
});

Solution 2:

Try using the javascript escape \'

Here's an excerpt from the jQuery docs that explains why your HTML escape character is being rendered:

By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, ). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

Solution 3:

Check this link: HTML-encoding lost when attribute read from input field

you can use the function that Anentropic write.

functionhtmlEscape(str) {
    returnString(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

Solution 4:

Thanks go to Barmar for providing the first correct answer. In actual fact I refactored my code so that I wasn't passing complicated strings via a method parameter, but my you did answer my initial query correctly.

Thanks to other comments for your input too.

Post a Comment for "Dynamically Changing The Html Of A Div With Jquery Is Causing Html Encoding To Be Lost"