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');
});
1

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.