1

Let's say I have the following div:

<div class="device iphone5 black"></div>

I want a toggle button to change devices. Therefore, the classes should be changed. But, not only .iphone5 should be replaced, the color .black should be replaced as well.

I have the following array:

var devices = [
            '.iphone5 .black',
            '.nexus5',
            '.iphone4s .black',
            '.lumia920 .blue',
            '.s5 .white',
            '.htc-one'
        ];

How can I make a switcher that checks if a div with the .device class has one of the classes defined in the array, and then replace it by the next one? Something like:

<script>
$('.device').filter(devices.join())$('.device').is(devices.join("")
        .attr('class', 'device ' + devices[NEXT]);
</script>
0

1 Answer 1

2

Loop through the array, searching for all elements that match the current selector, and replacing the classes with the next array element.

You have to loop through the array in reverse. Otherwise, after you change .iphone5.black to.nexus5, the next iteration will change that to .iphone4s.black, and everything will end up with the last class in the array.

for (var i = devices.length-2; i >= 0; i--) {
    $(".device" + devices[i]).attr("class", "device " + devices[i+1].replace(/\./g, ' '));
}

Also, you need to take the spaces out of the values in devices. .iphone5 .black means to search for a child of .iphone5 with class black, but you want these classes to apply to the same element, so it should be .iphone5.black.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works perfectly. Only need to figure out how to run the loop over and over again. Should I reset i at the end?

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.