0

I use a tooltip library where I escape HTML and place it in the title attribute. When you mouse over that element, it unescapes the HTML and places it in the tooltip.

The issues I'm having is recursion. I have a button in a tooltip, that also has a tooltip. Ex:

nested_toooltip = "<h1>Hi, I'm a tooltip</h1>"
tooltip = '<a title="' + escapeHtml(nested_tooltip) + '">Button</a>"
document.write('<a title="' + escapeHtml(tooltip) + '">Button</a>"')

When you create the first tooltip, it unescapes ALL of the tooltips. And I essentially get malformed HTML. Is there a clever way to do this where HTML can essentially be escaped twice? Because escapeHtml(escapeHtml(string)) produces the same result as escapeHtml(string).

Bart
  • 19,692
  • 7
  • 68
  • 77
Binary Logic
  • 2,562
  • 7
  • 31
  • 39

1 Answers1

0

You need a proper escapeHTML function (equivalent to PHP's htmlentities()).

function escapeHTML(s){
    var d = document.createElement("div");            //Container
    d.innerHTML = "<a></a>";                          //Placeholder
    d.firstChild.setAttribute("title", s);            //Setter
    return d.innerHTML.match(/^<a[^"]+"([^"]*)"/i)[1];//Returns entitied html
}

Explanation of code:

  • Create a container
  • Store a dummy element in it (<a> in this case)
  • Use the setAttributw method on the dummy element to set an attribute
  • Get the .innerHTML property of the container. This will return the dummy element plus the entitied string. Strip the dummy element, and return the "escaped" string.
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • This works, is there a recursive way to do this? Where the might be more than one title attribute? – Binary Logic Nov 21 '11 at 19:05
  • Replace your current `escapeHTML` function by my suggested code. If you really need a recursive function, add a second argument `depth`, and replace the last line by `return depth > 0 ? escapeHTML(s, --depth) : s;`. – Rob W Nov 21 '11 at 20:10