Javascript element giving text from before it was updated

  html, javascript

I’ve just been trying to make some code to test out tampermonkey stuff on simple maths questions when I came across this error. it would work for the first question, get the question, solve it, enter the answer. The element then changes to a new question however when I use .innerHTML or .textContent it always gives the original question.

Here is my code which shows this:

console.log(document.getElementById('currgamename'))
console.log(document.getElementById('currgamename').textContent)

I get this output:

<span id="currgamename">12-7</span>
6-3 //The first question that appears

Full code:

var delayInMilliseconds = 1000; //1 second

    var x = 0

    setTimeout(function() {
        var handler = setInterval(function() {
            document.getElementById('playPadding').childNodes[1].click()
            var equation = document.getElementById('currgamename').textContent
            var actual = equation.split('-')
            var answer = (parseInt(actual[0]) - parseInt(actual[1])).toString()
            document.getElementById('currgamename').innerHTML = 'hello'
            console.log(document.getElementById('currgamename'))
            console.log(document.getElementById('currgamename').textContent)
            document.getElementById('gameinput').value = answer
            document.getElementById('nextButton').click()
            x++;
            if (x >= 5) {
                clearInterval(handler);
            }
        }, 1000);
    }, delayInMilliseconds);

I have absolutely no clue why it gives the updated element but not the updated text so I could really use some clarification here thanks!

Source: Ask Javascript Questions

LEAVE A COMMENT