1

I want to control some css rules for elements using class names, for example there could be one 'class parameter' like 'setwidth200', number after 'setwidth' could be any number. There would be no problem for me to make this if I would know that element could have only one class, but currently it could look like this:

<div class="main-client-block selector righted setwidth200"></div>

Is there any ways to get only specific class from list of element classes?

Dazvolt
  • 697
  • 2
  • 10
  • 22

3 Answers3

1

Yes it is. Just add id to your div and then:

<div id="someId" class="main-client-block selector righted setwidth200"></div>

var classes = jQuery('#someId').attr('class').split(' ');

And You will get the array of classes of the element. Then You can get any class. Also what You might want to do is check if array contains your "class" and then split it for attribute and value to apply styles.

But why don't You simply use css for this?

patrykf
  • 449
  • 5
  • 19
  • I could use css for that, but there is too much elements on page, and no grid for positioning, I'm tired of adding css-classes over and over again. Thank you for idea. – Dazvolt Aug 27 '14 at 08:43
1

You can by looping through all the classes and check if something like setwidth is set. Something like this will do:

JavaScript:

$("div").each(function () {
    var check = "setwidth";
    var classes = $(this).attr("class").split(/\s+/);
    var width = 0;
    $.each(classes, function (index, item) {
        if (item.indexOf(check) === 0) 
            width = parseInt(item.substr(check.length), 10);
    });

    console.log(width);
});

FIDDLE

ZiNNED
  • 2,620
  • 20
  • 31
1

Moving comments to answer:

Having "number after 'setwidth' could be any number" is not a good way to use CSS (it will not use CSS, but just uses the class attribute as data storage).

Use attributes, like data-width="200" etc instead if you want to adjust/obtain a width value from code.

You can fetch them with .data (data prefix assumed) or .attr('data-...)`

var width = ~~$element.data('width');

or

var width = ~~$element.attr('data-width');

Note ~~ is a very quick way to convert a string to an integer.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202