 <p>Because you 1. Didn't include jQuery in your fiddle, and 2. had a typo in your code. New fiddle: <a href="https://jsfiddle.net/yx0ehdy5/2/" rel="nofollow noreferrer">https://jsfiddle.net/yx0ehdy5/2/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var idName = $('.a').closest('li').attr('id'); $('.a').attr('id', idName + 'B');</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul&gt; &lt;li id="a"&gt; &lt;div class="a"&gt;something &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>