Heshan Galahitiyawa Heshan Galahitiyawa - 6 months ago 30
Javascript Question

Sidr - remove prefix from all the children classes using jQuery

I need to remove the prefix 'sidr-class-' from all the classes inside the 'sidr-inner' parent div. Sidr provides an option to remove all the prefixes, but it removes prefixes from ID's as well. I want to remove only the class prefixes. The HTML is as follows:



<div class="sidr-inner">
<div class="sidr-class-col-sm-12">
<h2>Search by location</h2>
<form>
<input type="search" class="sidr-class-form-control" placeholder="Your location / postal code">
<button type="submit" class="sidr-class-btn sidr-class-btn-default">Search</button>
</form>
</div>
</div>





At the moment I'm using the following jQuery snippet to search and add classes, but it's not convenient to do it with a large number of classes.



$(document).ready(function(){
if($('div').hasClass('sidr-class-col-sm-12')) {
$('.sidr-class-col-sm-12').addClass('col-sm-12');
}
});





Anyone have an idea how to get this done using jQuery or Javascript? Thanks in advance!

Answer

you can try this code:

$(document).ready(function(){
  $('.sidr-inner [class*="sidr-class"]').each(function(){
    var old_classes = $(this).attr('class');
    old_classes = old_classes.replace(/sidr-class-/g, '');
    $(this).attr('class', old_classes);
  });
});

or this code:

$(document).ready(function(){
  $('.sidr-inner [class*="sidr-class"]').each(function(){
    $(this).attr('class', change_class);
  });
});

function change_class(i, v)
{
    return v.replace(/sidr-class-/g, '');
}

to solve your problem.

Comments