Friday, September 7, 2018

How do I change an Element's Class in JavaScript?

You can manipulate an element in jQuery by selecting it by its class, like so...

$(".SomeElementClass").SomeAction(...)

The period here indicates that "SomeElementClass" will match on elements like this...

<element class="SomeElementClass">

If you want to change the class, things can become a bit more tricky, but it is very possible...

const element = $('.SomeElementClass');
element.classList.remove('SomeElementClass');
element.classList.add('BrandNewClass');

Now, when looking at the DOM, your element will now be...

<element class="BrandNewClass">

The same approach can be used to change an element's id attribute, as well.

No comments:

Post a Comment