Artefact2
Artefact2

Reputation: 7634

Escaping of attribute values using jQuery.attr()

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&#10;bar">baz</div>

But this:

<div>baz</div>
<script>
$("div").attr('title', 'foo&#10;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

Answers (4)

Esailija
Esailija

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

http://jsfiddle.net/t5DvY/


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 &lt; 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 &#x2665;, you can simply write . Instead of writing &#x00F6;, you can simply write ö. Here's http://jsfiddle.net/fnqDn/2/.

Upvotes: 19

pat34515
pat34515

Reputation: 1979

This function will save you time, if you'll be doing this a lot:

function unescp(x){
 return $('<div/>').html(x).text();
}
$("div").attr('title',unescp('foo&#10;bar'));

See it here: http://jsfiddle.net/9Lnru/

Upvotes: 5

spinningarrow
spinningarrow

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&#10;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&#10;bar').text();
    $("div").attr('title', title);
</script>

Or on one line:

$('div').attr('title', $('<div/>').html('foo&#10;bar').text());

Upvotes: 15

Andreas Nilsson
Andreas Nilsson

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

Related Questions