2

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');
});
Jeroen
  • 1,168
  • 1
  • 12
  • 24
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • possible duplicate of [jQuery hasClass() - check for more than one class](http://stackoverflow.com/questions/2214952/jquery-hasclass-check-for-more-than-one-class) – Stephan Weinhold May 08 '15 at 09:10

3 Answers3

8

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');
Ram
  • 143,282
  • 16
  • 168
  • 197
1

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>
j08691
  • 204,283
  • 31
  • 260
  • 272
0

Just iterate through the array, to check for each class:

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

Demo: http://jsfiddle.net/e6mds7vz/1/

agconti
  • 17,780
  • 15
  • 80
  • 114