Valentin Zambelli
Valentin Zambelli

Reputation: 149

Access html elements created by js in other js functions

I am trying to access html elements that I create in one js function in another function. I have this code

EDIT after comments: here is a jsfiddle http://jsfiddle.net/8uTxM/

</button>" +"<button value='1' type='button' class='as' id='c2' onclick='cA(this);'>"

in this function

function cA (element){
var x = element.value;

if (x === allQuestions[questionNumber].correctAnswer) {
    element.setAttribute.style.backgroundColor = "green";
    ++score;
    }
} 

I am trying to make the button green when it is clicked. However, I get the error: Cannot set property 'backgroundColor' of undefined

I assume this has something to do with timing, but I cannot figure out why. Especially since the element.value bit works (the++score works fine, every right question adds +1 to the score variable)

Upvotes: 0

Views: 71

Answers (2)

Anup Singh
Anup Singh

Reputation: 1563

One problem that I may guess is you are using "getElementsById"

either go for "getElementById" or "getElementsByTagName"

Upvotes: 1

user3807702
user3807702

Reputation: 55

Why don't you create a <div> in your html/php page which would be empty with the answers class, and then change its id/innerHTML ?

Upvotes: 0

Related Questions