 <p>This happens because you are running in 'this' context. As a result what ever you changing in $(this) will get hoisted to top of the function. A simple example:</p> <pre><code>$('#txt').click(function () { console.log(this); var a = 10; var b = 20; var c = a+b; console.log(c); $(this).text('changed!'); $(this).attr('test','test'); }); </code></pre> <p>will hoist at the top</p> <pre><code>$(this).text('changed!'); $(this).attr('test','test'); </code></pre> <p>and the result will be</p> <pre><code>&lt;div id="txt" test="test"&gt;changed!&lt;/div&gt; 30 </code></pre> <p><a href="http://jsfiddle.net/oeaw9mLy/" rel="nofollow">JSFiddle</a></p>