javascript - want to remove a previously added class and add a new class to the same div -
i making frombuilder in on choosing option value (from 1 12) adds col-xs-(1-12) class div. when want choose other option add different col-xs-(1-12) class previous class doesn't deleted.
function addgrid() { console.log("addgrid called !"); console.log($(".grid_cols").val()); var col_val = $(".grid_cols").val(); console.log("col_val :" + col_val - 1); if ($(".fb-field-wrapper").find('col-xs' + '-' + col_val)) { console.log("hasclass ??"); $(".fb-field-wrapper").removeclass('col-xs' + '-' + col_val); console.log("removed class"); } else { $(".fb-field-wrapper").addclass('col-xs' + '-' + col_val); } }
you may also:
- use bit of regex see if class of pattern
col-xs-<num>
exists - if yes, remove it
- add new class
here code, simplified above points.
function addgrid() { var col_val = $(".grid_cols").val(), $wrapper = $(".fb-field-wrapper"), matches = $wrapper.attr("class").match(/col-xs-(\d+)/i); //see if class 'col-xs-<num>' exists if (matches !== null) { //if yes, remove class $wrapper.removeclass("col-xs-" + matches[1]); } //add class $wrapper.addclass('col-xs' + '-' + col_val); }
note: in code, $(".fb-field-wrapper").find('col-xs' + '-' + col_val)
try find children of .fb-field-wrapper
class col-xs-<num>
whereas wanted see if class exists in wrapper itself. that, you'd do:
if ( $(".fb-field-wrapper").hasclass('col-xs-' + col_val) ) { ... }
Comments
Post a Comment