When using jQuery to update the title attribute of an element, I find that the entities (notably , which is the currently recommended way of adding line breaks in the title attribute) do not display correctly (the entity shows up as text, and is not parsed…).
For example:
<!-- This works fine -->
<div title="foo bar">baz</div>
But this:
<div>baz</div>
<script>
$("div").attr('title', 'foo bar'); // Escapes the &
</script>
Is there a way to not have jQuery escape the value? I tried using unescape() before .attr(), but it didn’t work…
You are right;
unescape()will not work in this case. What you can do is something similar to what is mentioned in the answer here.Basically, create an empty element using jQuery, set it’s HTML to the text you want in the title (
'foo bar'in this case) and then get back the element’s text.Sounds a little complicated? It is, but this will work for any HTML entity and it’s really just a one-liner. Here’s the code:
Or on one line: