estevan gomez estevan gomez - 6 months ago 22
jQuery Question

jQuery Find and Replace all instances of part of a classname

I have several div's with a classname that looks like this:

class="col-md-4"


some have:

class="col-md-12"


What I want to do is to search for whatever the number at the end of the class is and replace all of them to:

class="col-md-6"


How can I do this using jQuery?

Answer

you can use "begin with" selector like this

$("[class^='col-md-']").removeClass (function (index, css) {
    return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");

removeClass function based on this answer

$("[class^='col-md-']")

will find any element with a class that begins with col-md-. The removeClass function will than remove it. And finally col-md-6 will be added.