Reputation: 7634
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…
Upvotes: 13
Views: 17986
Reputation: 140220
jQuery isn't escaping anything, in fact your string is literally set as the title. You can simply use:
$("div").attr('title','foo\nbar')
There seems to be a whole lot of misunderstanding what escaping means. What you are doing is completely unnecessary.
Escaping is only necessary in a context where the character would otherwise have a special meaning and you want it not to have any special meaning.
For example, in the eyes of html parser, <
is special. You have to replace it with <
if you want to ensure it is treated as literal
<
. Emphasis on in the eyes of html parser. In javascript, <
is not special in a string in any way, thus you could
do elem.setAttribute("title", '""><b>hi</b>')
and that's what you get, the element's title will literally be ""><b>hi</b>
.
As for html code point references, they are generally useless. You can simply use literal characters. Instead of writing ♥
, you can simply
write ♥
. Instead of writing ö
, you can simply write ö
. Here's http://jsfiddle.net/fnqDn/2/.
Upvotes: 19
Reputation: 1979
function unescp(x){
return $('<div/>').html(x).text();
}
$("div").attr('title',unescp('foo bar'));
See it here: http://jsfiddle.net/9Lnru/
Upvotes: 5
Reputation: 2436
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());
Upvotes: 15
Reputation: 231
You could try to put the value in a hidden element. And let jquery copy that value to the div. Im not sure if it would pass through jQuery unnoticed, but it's worth a try...
Upvotes: 0