user2367836
user2367836

Reputation: 61

Escape "<" and ">" as part of element attribute value in IE

I want to escape ">" and "<" inside an element attribute and unfortunately I could not figure it out. It looks that by default in IE outerHTML is escaping ampersand character and once I try to escape ">" (replace ">" with "amp+gt;") the ampersand that is part of "amp+gt;" is escaped again. Here is a sample code:

        var div = '<div atr="test & and < and >"></div>';            
        var $el = $(div);
        console.log("txt string: " + div);
        console.log("$el outerHTML BEFORE escaping: " + $el[0].outerHTML);

        var rgx = new RegExp(">", "g");
        $el.attr("atr", $el.attr("atr").replace(rgx, "&gt;"));
        console.log("$el outerHTML AFTER escaping: " + $el[0].outerHTML);

This is the output from this code:

txt string: <div atr="test & and < and >"></div>
$el outerHTML BEFORE escaping: <div atr="test &amp; and < and >"></div>
$el outerHTML AFTER escaping: <div atr="test &amp; and < and &amp;gt;"></div>

As one can see ampersand that is part of greater then escaped is escaped again. Basically what I need to have is:

<div atr="test &amp; and < and &gt;"></div>

Would you please let me know what might be missing here and how to fix this?

Thank you.

Upvotes: 0

Views: 262

Answers (1)

Alnitak
Alnitak

Reputation: 339917

Just use the .attr method to set the attribute and the contents will be escaped automatically:

> $('<div>').attr('foo', '<>')[0].outerHTML
"<div foo="&lt;&gt;"></div>"

NB: this is one of the reasons why it's good to use jQuery methods to modify elements instead of string concatenation.

Upvotes: 1

Related Questions