Escaping of attribute values using jQuery.attr()
html, javascript, jquery
Solution
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:
<div>baz</div>
<script>
var title = $('<div/>').html('foo bar').text();
$("div").attr('title', title);
</script>
Or on one line:
$('div').attr('title', $('<div/>').html('foo bar').text());
Problem
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…