Heekei Heekei - 1 year ago 129
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
and second to
using jquery dynamicaly.
I don't know how to handle it in Javascript.

How can i do this work?

Answer Source

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.

    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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download