I never thought I’d write a “considered harmful” post, but this is really way too serious.
Do not use jQuery 1.4 or 1.4.1 with user generated content!
jQuery 1.4 branch added some great stuff, but let a really ugly bug through. Something that you could call jQuery injection.
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !jQuery.isFunction( value ) ) {
value = jQuery( value ).detach();
}
...
With previous versions you could easily do $('#myElement').replaceWith('some text');
to replace the selected node with a text node. In jQuery 1.4 and 1.4.1 you can’t – but just failing does not constitute a huge bug.
If you take a good look at the code above you can easily find that if value
passed is a string
that looks like a selector, it will detach nodes from the document. Consider calling $('#myElement').replaceWith('html');
– the screen goes blank and everything the user has been working on is gone.
Fortunately…
jQuery 1.4.2 fixed this issue by properly using detach only when value
is not a string
. If you are using jQuery 1.4 or 1.4.1 and for some reason cannot upgrade to 1.4.2 (or just don’t want to), you can still just copy the whole replaceWith
method from jQuery 1.4.2 to your version.
Related articles by Zemanta
- 101 on jQuery Selector Performance (java.sys-con.com)
- It’s Easy to Fall in Love with jQuery (sitepoint.com)
- jQuery: Novice to Ninja (oreilly.com)