Solution 1 :

I am not sure from the question whether the requirement is to remember just the current and previous colors, or whether the requirement is to remember them all over all time.

Assuming it’s the first, this snippet just adds a line to save the current color in another data attribute, data-prev, before updating it with the new color. We could, for example, make sure that the same color isn’t chosen twice running at this point.

The snippet writes the previous and current colors to the console so we can check it’s working.

window.getRandomNumber = function (max) {
    return Math.floor(Math.random() * max)

var colors = ['red', 'blue', 'green', 'orange', 'purple'];
const changeHeadlineColor = function (croHeadline) {
    var random = getRandomNumber(5000);
    var randomString = random.toString();
    setTimeout(() => {
        var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0));
        croHeadline.setAttribute('data-prev', croHeadline.getAttribute('data-color')); //remember the current color
        croHeadline.setAttribute('data-color', colors[colorKey]);
        console.log(croHeadline.getAttribute('data-prev') + ' ' + croHeadline.getAttribute('data-color'));
    }, random);

    [data-color="red"] { color: red; }
    [data-color="blue"] { color: blue; }
    [data-color="green"] { color: green; }
    [data-color="orange"] { color: orange; }
    [data-color="purple"] { color: purple; }
<div data-color="red">SOME TEXT</div>

Problem :

I’m trying to get the previous and current color of an element and can’t figure out how to do that. Any suggestions would be greatly appreciated!


Comment posted by aloha

The code looks like it’s used to change random color of Headline each random time when calling the changeHeadlineColor function infinity loop, But I don’t really understand your question, Why do you need to get previous and current color, can you specify more