Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if elements has class which is given in a list/array

I need to add to specific elements of a list the class .disabled. These elements can be found in an array or something like that - don't know what is recommended for this.

HTML:

<ul id=anything>
    <li><a href="javascript:;" class="re-icon re-deleted"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-bold"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-italic"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-table"></a> Text</li>
</ul>

This should become this:

<ul id=anything>
    <li><a href="javascript:;" class="re-icon re-deleted"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-bold disabled"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-italic"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-table disabled"></a> Text</li>
</ul>

JS:

var arr = ['re-bold', 're-table'];
$('#anything a').each(function() {
    if ( $(this).hasClass('anything of the array') ) { // Check if this element has a class, which is given in the array
        $(this).addClass('disabled');
});
like image 472
user3142695 Avatar asked Feb 13 '26 08:02

user3142695


2 Answers

You could add a . to the array's elements, either manually or by using the Array.prototype.map method. and join the array's elements. Then filter method will filter the matching elements according to the created selector:

var arr = ['.re-bold', '.re-table'];
$('#anything a').filter(arr.join()).addClass('disabled');
like image 199
undefined Avatar answered Feb 15 '26 21:02

undefined


One way:

var arr = ['re-bold', 're-table'];
$('#anything a').each(function () {
    for (var i = 0; i < arr.length; i++) {
        if ($(this).hasClass(arr[i])) $(this).addClass('disabled');
    }
});

jsFiddle example

Produces:

<ul id="anything">
    <li><a href="javascript:;" class="re-icon re-deleted"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-bold disabled"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-italic"></a> Text</li>
    <li><a href="javascript:;" class="re-icon re-table disabled"></a> Text</li>
</ul>
like image 29
j08691 Avatar answered Feb 15 '26 22:02

j08691



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!