0
votes

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).

1
please provide us the tooltip libary you use - Frederick Behrends
Show the source for function escapeHTML. - Rob W
It is possible to do tooltips with CSS which would easily solve your problem unless there is some reason you need to use dynamically created ones. - qw3n

1 Answers

0
votes

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.