Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do jQuery's val() and prop() methods html-escape values?

I can't find anything in the documentation about val() and prop() and escaping.

Are they intended to escape values when used as setters?

like image 673
Matt Fenwick Avatar asked May 15 '12 15:05

Matt Fenwick


People also ask

Does jQuery val escape?

jQuery - text( val ) Method The text( val ) method sets the text contents of all matched elements. This method is similar to html( val ) but escapes all HTML entities.

How do I escape HTML data?

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

What is val () in HTML?

The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


2 Answers

Not really. .val() is used to set a form field's value attribute, so escaping isn't really necessary there. You'll be setting the value via the DOM, so it's not like you're constructing HTML through string concatenation. .prop(), on the other hand, doesn't even interact with attributes at all - just DOM properties, so you don't need to working about HTML escaping their either.


Edit: for the sake of clarification, I'm assuming that you're asking this because you're concerned about .prop() or .val() as an XSS attack vector (or just an opportunity to shoot yourself in the foot)? If that's the case, you need to remember that when setting attributes and properties via the DOM, the values that you set are essentially sandboxed to the attribute or value you were interacting with. For example, given the following:

<div id="foo"></div> 

And you attempted to abuse an attribute value, such as:

$('#foo').attr('rel', '"></div><script>alert("bang");</script><div rel="'); 

You might be concerned that this would result in something like the following:

<div id="foo" rel=""></div><script>alert("bang");</script><div rel=""></div> 

This will never happen, though. You will indeed have a rel attribute with the evil-looking string as its value, but no new markup or DOM nodes will be created. The string itself isn't escaped - it's just simply not interpreted as markup. It's just a string and that's it.

like image 58
jmar777 Avatar answered Oct 05 '22 16:10

jmar777


They expect strings, not HTML. You don't need to escape anything.

The methods themselves don't do any escaping either, the underlying DOM APIs they use also deal in strings, not HTML.

Once you start using JavaScript you almost never need to worry about HTML syntax, the only exception I can think of is when dealing with the innerHTML property which explicitly deals with (de)serialising the DOM to and from HTML.

like image 21
Quentin Avatar answered Oct 05 '22 16:10

Quentin