Heekei Heekei - 2 months ago 22
CSS Question

set style by special classname

I'm ready to make a tool to improve my work.

I don't know how to describe it in English.

Please look at the code.



.container{
margin:0 auto;
}

<div class="container width-300">

</div>





I want to set the div's width to 300px by this way.

I don't know how to handle it in Javascript.

Or is there existing any tools what can achieve it?

Answer

You need to find element has class width-* that * should be only digit. You can use .match() to check class name. If class name is right, add digit of class to width of element.

$("[class*=width-]").each(function(){
    var match = $(this).attr("class").match(/width-([\d]+)/);
    if (match)
        $(this).css("width", match[1]);
});
div {
    background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="width-100">100</div>
<div class="width-200">200</div>
<div class="width-300">300</div>