⊗jqDmCEA 42 of 113 menu

Adding a Class to an Element in jQuery

Let me remind you that in the attribute class in the HTML code you can write several classes separated by spaces.

Let's imagine this situation - you want to add a new class to the existing ones without overwriting them. In this case, simply doing .attr('class', 'new-class') won't work (using the attr method) - you'll overwrite the classes that are already in the attribute.

Of course, you can first count the classes that are there, then add our class to them separated by a space and write everything back to the attribute, but there is an easier way - jQuery has a method for such things addClass.

The addClass method allows you to add a class to an element (or elements) without overwriting other classes. The class you want to add to the element is passed as a parameter to this method.

In the following example we have an element with two classes - class="www zzz":

<p class="www zzz" id="test">text</p>

We can add a third class to it - kkk. As a result, the attribute content will become like this - class="www zzz kkk":

$('#test').addClass('kkk');

HTML the code will look like this:

<p class="www zzz kkk" id="test">text</p>

Add all li class test.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline