Heekei Heekei - 2 months ago 11
Javascript Question

How to add style relevant to class name to element using jquery?

I'm ready to make a tool to improve my work. Please look at the code.

<div class="container width-200"></div>
<div class="container width-300"></div>




I want to set the first div width to
200px
and second to
300px
using jquery dynamicaly.
I don't know how to handle it in Javascript.

How can i do this work?

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>

Comments