How can I delete a class which starts with a specific string?

Tags: jquery
Question!

I want to remove a class which starts with "num" in jquery. Is that posible? I've tried to use ^= but it doesn't work. Thank you very much

    $(".dice-roller").click(function() {
      $("[class^='dot']").remove();
      
      $(".dice").removeClass("num1 num2 num3 num4 num5 num6");

              
      var number1 = Math.floor((Math.random() * 6) + 1);
      var number2 = Math.floor((Math.random() * 6) + 1);
     

      for (var i = 0; i < number1; i++) {
        $(".d1").append("<span class='dot dot" + i + "'></span>");

      }
      if (!$(".d1").hasClass("num" + number1)) {

        $(".d1").addClass("num" + number1);
      }
      for (var i = 0; i < number2; i++) {
        $(".d2").append("<span class='dot dot" + i + "'></span>").addClass("num" + number2);
      }

      if (!$(".d2").hasClass("num" + number2)) {

        $(".d2").addClass("num" + number2);
      }
    });
    .dice:first-child{margin-right:20px;}
    .dice{width:100px; height:100px; background:black; border-radius:10px; float:left; position:relative;}
    .dice-roller{position:absolute; left:50%; top:50%; transform:translate(-50%, -50%); cursor:pointer;}
    .dot{width:15px; height:15px; border-radius:100%; background:#fff;display:inline-block; position:absolute;}

    .num1 .dot0{left:50%; top:50%; transform:translate(-50%, -50%);}

    .num2 .dot0{left:15px; top:15px;}
    .num2 .dot1{right:15px; bottom:15px;}


    .num3 .dot0{left:15px; top:15px;}
    .num3 .dot1{right:15px; bottom:15px;}
    .num3 .dot2{left:50%; top:50%; transform:translate(-50%, -50%);}

    .num4 .dot0{left:15px; top:15px;}
    .num4 .dot1{right:15px; bottom:15px;}
    .num4 .dot2{left:15px; bottom:15px;}
    .num4 .dot3{right:15px; top:15px;}

    .num5 .dot0{left:15px; top:15px;}
    .num5 .dot1{right:15px; bottom:15px;}
    .num5 .dot2{left:15px; bottom:15px;}
    .num5 .dot3{right:15px; top:15px;}
    .num5 .dot4{left:50%; top:50%; transform:translate(-50%, -50%);}

    .num6 .dot0{left:15px; top:15px;}
    .num6 .dot1{right:15px; bottom:15px;}
    .num6 .dot2{left:15px; bottom:15px;}
    .num6 .dot3{right:15px; top:15px;}
    .num6 .dot4{right:15px; top:50%; transform:translateY(-50%);}
    .num6 .dot5{left:15px; top:50%; transform:translateY(-50%);}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="dice-roller">
    <div class="dice d1"></div>
    <div class="dice d2"></div>
    </div>

This is my code



Answers

Option 1: Assuming your element's class name list really starts with class='num..' and not like class='test num..' and it only can occur once per element then you can keep it simple like that:

$('[class^="num"]').attr('class', function(i, val){
  return val.replace(/^num\S+/, '');
});

Explanation: You select all elements which begin with the wished class. Then you replace the class name with an empty string.

The regular expression for the replacing means: Select the word beginning with 'num' and any non whitespace character after it. Then delete it by replacing it with an empty string.

Fiddle: https://jsfiddle.net/j2345091/

See also: https://api.jquery.com/attr/ and https://api.jquery.com/attribute-starts-with-selector/

Option 2: If you want to cover also the cases where the class name occurs somewhere in the class list and it can be multiple times there too, then write:

$('[class*="num"]').attr('class', function(i, val){
    return val.replace(/(^|\s)num\S+/g, '');
});

it will select any element containing the wished class at the first place. The Regex here means: select any word starting with 'num' or 'num' after a blank. Then take any following non whitespace character and remove it by replacing it with an empty string. The 'g' at the end additionally makes sure several occurrences are handled.



You may create a new selector in order to select the elements having a class name starting with a string and .removeClass( function ) to remove the class starting with the that string:

jQuery.extend(jQuery.expr[':'], {
  hasClassStartingWith: function(a,i,m) {
    if(m[3] == '') {
      return true;
    }
    var result = $(a).filter(function() {
      var classNames = this.className.split(/\s+/);
      for (var i=0; i<classNames.length; ++i) {
        if (classNames[i].indexOf(m[3]) == 0) {
          return true;
        }
      }
      return false;
    });
    return (result.length == 0) ? false : true;
  }
});


//
// Use the selector and removeClass( function )
//

var classStartingWith = "num";

$('button:hasClassStartingWith("' + classStartingWith + '")').removeClass(function(i, c) {
  var classNames = this.className.split(/\s+/);
  for (var i = 0; i < classNames.length; ++i) {
    if (classNames[i].indexOf(classStartingWith) != 0) {
      classNames[i] = '';
    }
  }
  return classNames.join(' ');
}).each(function() {
  console.log(this.outerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button type="button" class="class1 num2 class3">Click Me</button>

<button type="button" class="class1 nuZm2 class3">Click Me</button>

By : gaetanoM


try this, from this you can get an idea. hope this will help to you.

<html>
<head></head>
<title></title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">

div{
  width: 100px;
  height: 100px;
  border: 3px solid black;
  margin: 10px;
  color: white;
  text-align: center;
  font-size: 20px;
  font-family: monospace;
}


.one{
  background-color: orange;
}

.two{
  background-color: purple;
}

.three{
  background-color: pink;
}

.four{
  background-color: yellow;
}



</style>

<body>

<div class="one">class name : one</div>
<div class="two">class name : two</div>
<div class="two">class name: two</div>
<div class="three">class name : three</div>
<div class="four"> class name : four</div>

<br>
<h2>Click on any div, it will remove the styles on class two only</h2>



</body>

<script type="text/javascript">

//to get you and idea , I will remove a specific class in a button click.
$("div").click(function(){
  //get the class name
  var the_class_name = $(this).attr('class');
  alert(the_class_name);

  // now I'm going to remove the class from two
  if(the_class_name == "two")
  {
    $("."+the_class_name).removeClass(the_class_name);
  }


});
 

</script>

</html>

By : Anuradh S


This video can help you solving your question :)
By: admin