Ricalsin
Ricalsin

Reputation: 940

jQuery selector on multiple classes

This finds the id but does not remove the class

$('[id^=paritalIDname]').removeClass('[class^=partialClassName]');

Probably because the element looks like

<div id="partialIDname-full" class="something someone partialClassNameFull">

Whether the element has a class name of partialClassNameFull or partialClassNameHalf I need to remove it.

I thought I could use a wildcard in the class selector, like

removeClass('[class^=partialClassName*]');

but that's not working.

What is a good solution? (Thanks.)

Upvotes: 1

Views: 842

Answers (2)

Jules
Jules

Reputation: 1423

This will handle all partial match.

        $("div[id^=partialId]").each(function () {
            var cls = $(this).attr("class").split(" ");

            for (var i in cls) {
                if (/partialClass/.test(cls[i])) {
                    $(this).removeClass(cls[i]);
                    break;
                }
            }
        });

Upvotes: 1

JK.
JK.

Reputation: 21809

You need to explicitly remove both classes:

$('[id^=partialIDname]').removeClass('partialClassNameFull').removeClass('partialClassNameHalf');

Because .removeClass() only works on full class name matches. If one of the class names is not present, then nothing will happen - no error is thrown when you try to .removeClass() a class that is not present.

You can also try out as suggested in the comments the briefer version of:

$('[id^=partialIDname]').removeClass('partialClassNameFull partialClassNameHalf');

Upvotes: 0

Related Questions