Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 17174  / 12 Years ago, sat, july 21, 2012, 12:00:00

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…


More From » jquery

 Answers
9

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());

[#84111] Thursday, July 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;