Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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…

like image 897
Artefact2 Avatar asked Jul 21 '12 09:07

Artefact2


People also ask

What is the use of attr () method in jquery?

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.

What is this ATTR?

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.

How do I escape HTML data?

To escape data for an HTML Attribute, use Laminas\Escaper\Escaper 's escapeHtmlAttr() method.


1 Answers

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/.

like image 62
Esailija Avatar answered Oct 22 '22 00:10

Esailija