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…
The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.16-Sept-2022.
To escape data for an HTML Attribute, use Laminas\Escaper\Escaper 's escapeHtmlAttr() method.
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 <
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With