-1

My HTML code:

<div class="container">
<div class="question-card">
    <h1 id="question1">This is the question</h1>
</div>
<div class="answer-choices">
    <div class="row1">
        <span class="choice1" id="one" onclick="choice1()">One</span>
        <span class="choice2" onclick="choice2()">Two</span>
    </div>
    <div class="row2">
        <span class="choice3" onclick="choice3()">Three</span>
        <span class="choice4" onclick="choice4()">Four</span>
    </div>      
</div>
<button id="btn" onclick="next()">Next</button>

My js code:

function clickNextText(){
    document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
}   //This is working fine


var str
element = document.getElementById('btn'); 
if (element != null) {
 str = element.value;
}
else {
      str = null;
}
console.log(str)  //This is however returning null. 

I don't understand what is wrong here. Moreover every element with an id after the div with class answer-choices isn't detected. While the script code when placed in .html itself works fine.

Tibrogargan
  • 3,599
  • 3
  • 16
  • 33
Anurag Bannur
  • 23
  • 1
  • 7
  • 1
    Where are you including the JS file? – jhpratt Jul 15 '18 at 03:36
  • The code in your external file is running when the browser loads it. Since this is probably in the `head`, none of the DOM elements exist yet, so `getElementById` will fail. There is a chance you could get away with deferring your script load, but the solution is not to have bare code in an external script that refers to the DOM. – Tibrogargan Jul 15 '18 at 03:39
  • That is exactly what is happening. Thanks! – Anurag Bannur Jul 15 '18 at 03:46

2 Answers2

0

Likely your javascript is running before the page has loaded. Try wrapping your whole javascript logic in a function and running it on window.load.

i.e.

window.load = function () {
// your code here
}
MynockSpit
  • 399
  • 4
  • 10
0

first change your function name on click from next() to clickNextText()

<button id="btn" onclick="clickNextText();">Next</button>

then use this code in javascript instead of :

function clickNextText(){
document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
}  

document.onload = function(){
var str
element = document.getElementById('btn'); 
if (element != null) {
   str = element.value;
}
else {
   str = null;
}
console.log(str);
};