Rob is correct that using addClass is the preferable way to go for classes,
and attr is the preferable way to go for other attributes. They are both
are safe since they use setAttribute internally which escapes the values.
- Trevor
On Tue, Aug 28, 2012 at 10:29 AM, Rob Lanphier <robla(a)wikimedia.org> wrote:
On Mon, Aug 27, 2012 at 9:39 PM, Chris Steipp
<csteipp(a)wikimedia.org>
wrote:
On Mon, Aug 27, 2012 at 4:37 PM, Mark Holmquist
<mtraceur(a)member.fsf.org>
wrote:
I also
tried to get an answer about the better between $( '<div
class="a-class" />' ) and $( '<div />' ).addClass(
'a-class' ), but
apparently there's little difference. At least when creating dynamic
interfaces, I'd like to have some guidance and consistency if anyone is
interested in chatting about it.
I'm going to try and put some guidelines for secure javascript code
together soon, but it's a much better habit to use .addClass(
'a-class' ) and the other functions to add attributes.
To clarify this point, in that *specific* example, there's no
appreciable difference from a security perspective.
The problem comes when you move out of the land of constants, and
start concatenating variables. Any time you find yourself doing
something like this:
$( '<div class="' + fooclass + '" />' );
...you're way better off doing this:
$( '<div />' ).addClass( fooclass );
Not only is it clearer, but it's more secure. Why? If the provenance
of that variable is at all unclear, or if you know it comes from user
input, I believe you're basically using the DOM to make sure that the
string is treated as a class name rather than arbitrary HTML
(Arbitrary HTML leads to XSS. XSS leads to anger. Anger leads to
hate....). I don't know jQuery well enough to know for sure if using
addClass is sufficient for arbitrary strings or if it's best to *also*
escape fooclass, but it's at least more likely to be safe than
concatenating to arbitrary HTML.
If you're dealing just with a constant string, maybe it's ok to use
either. However, sooner or later, someone is going to want to make a
small tweak that involves changing part of the constant to a variable,
and there's a good chance that someone is going to be relatively
inexperienced and will simply rely on concatenation rather than
changing the code to use addClass.
Even if addClass doesn't inherently handle the escaping for you, a lot
of basic DOM methods do, which is what makes them appealing from a
security perspective. The more specific you can be, the better.
Rob
_______________________________________________
Wikitech-l mailing list
Wikitech-l(a)lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l