Spiro Spiro - 9 months ago 36
jQuery Question

How to get element class by prefix via jQuery

What is the best way to get an element class by prefix?

For example I have:

<div class="cc-colour-red cc-size-big cc-width-narrow">

How to get those separately - the colour, te size and the width?

I hope that makes sense.

I have the DOM element selected. The final result would be "big", "red" and "narrow".



Try this:


$("div").each(function(index, elem){
  var classes = $(elem).attr("class");
  var color = classes.replace(/.*cc-colour-([^\s]+).*/g, "$1");
  var size = classes.replace(/.*cc-size-([^\s]+).*/g, "$1");
  var width = classes.replace(/.*cc-width-([^\s]+).*/g, "$1");
  console.log(color, size, width); //red big narrow, blue small wide, green medium narrow


<div class="cc-colour-red cc-size-big cc-width-narrow">
<div class="cc-colour-blue cc-size-small cc-width-wide">
<div class="cc-colour-green cc-size-medium cc-width-narrow">