0

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)

3
  • General remark: A HTML element's ID must not start with a number. (see stackoverflow.com/questions/70579/…). Most browsers will probably tolerate it, but it's better to avoid going against the rules. Commented Jul 28, 2014 at 9:22
  • 1
    First off, its getElementById not getElementsById. Second, if you use on click you should define your function as a function (onclick="functionName();"). Third, you could try passing the this to your function and eliminating the need for separate functions altogether: onclick="setIndId(this);", and then passing it your function function setIndId(element){ element.setAttribute("id",0+questionNumber)}. But it's very complicated to figure out like this, so please provide a fiddle or a reference to your code somewhere (if it is readable and not over complex) Commented Jul 28, 2014 at 9:22
  • added jsfiddle in original post Commented Jul 28, 2014 at 9:50

2 Answers 2

1

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

either go for "getElementById" or "getElementsByTagName"

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

Comments

0

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 ?

1 Comment

I create the div dynamically to hide it more easily. each div gets assigned the question number. When the next button is clicked, the current question is assigned a .hidden class.

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.