Dazvolt
Dazvolt

Reputation: 697

Jquery get specific class of element

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?

Upvotes: 1

Views: 1705

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

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.

Upvotes: 1

ZiNNED
ZiNNED

Reputation: 2650

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

Upvotes: 1

patrykf
patrykf

Reputation: 449

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?

Upvotes: 1

Related Questions