I'm trying my hand at Javascript and interacting with the DOM for the first time by making a simple quiz game. All of my elements are generated dynamically by JS except a few divs.
so here is my problem.
I have
Question 1.
(A)
(B)
(C)
(D)
I want to be able to click on any of the answers and have the values returned. To do that, I wrote the function
function checkCorrectness(element){
element.onclick = function(){
nodes = element.childNodes
for(i = 0; i<nodes.length; i++){
nodes[i].onclick = function(){console.log(nodes)};
}
}
}
//Note answers selectsthe div containing the 4 <p> elements A,B,C,D
checkCorrectness(answers)
Which returns me, as expected, an array of the four
elements containing my answers. So, I thought the logical next step would be to select the particular node onClick by changing it by console.log-ing nodes[i] instead of nodes. I would expect this to return me the element which I clicked on, so I could compare its inner HTML to the correct answer, therefore seeing if it was the right answer.
function checkCorrectness(element){
element.onclick = function(){
nodes = element.childNodes
for(i = 0; i<nodes.length; i++){
nodes[i].onclick = function(){console.log(nodes[i])};
}
}
}
checkCorrectness(answers)
However, it just returns undefined. Any help would be much appreciated!