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)

  • General remark: A HTML element's ID must not start with a number. (see http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html). Most browsers will probably tolerate it, but it's better to avoid going against the rules. – UweB Jul 28 '14 at 09:22
  • 1
    First off, its getElementById not getElement*s*ById. 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) – somethinghere Jul 28 '14 at 09:22
  • added jsfiddle in original post – Valentin Zambelli Jul 28 '14 at 09:50

2 Answers2

1

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

either go for "getElementById" or "getElementsByTagName"

Anup Singh
  • 1,423
  • 2
  • 15
  • 29
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 ?

  • 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. – Valentin Zambelli Jul 28 '14 at 09:52