1

I am working on the lap feature for a stopwatch on a web page. The idea is that there is a div to which the current time will be appended whenever you click to record a lap. However, I'm getting null back from the getElementById function when I try to reference the lapLog div. I know that the page must be fully loaded for all elements to be discoverable, which is why I placed the function called by the button inside a $(document).ready block, but in spite of this it's still returning null.

Relevant JavaScript (timer.js):

$(document).ready(function(){ $('#lapClkBtn').click(function(){ // Only allow laps to be recorded if the timer is running if (ClkTimer.isAlive() == true) { var newEntry = ClkTimer.recordLap(); lapLog = document.getElementById('lapLog'); lapLog.innerHTML.append(newEntry); lapLog.animate({ scrollTop: lapLog.prop('scrollHeight') }, 100); } }); }) function clkTimer(text, updateinterval) { this.recordLap = function() { this.lapNum = this.lapNum + 1; return String(this.lapNum) + "| " + this.formattedTime() + "<br>"; } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" id="lapClkBtn">Lap</button> <div class="lapLog"></div>

1
  • in the consloe you can see ReferenceError: Can't find variable: ClkTimer your function is clkTimer Commented Dec 8, 2017 at 17:17

1 Answer 1

4

Your laplog is used as class. getElementById finds the element by the given id, not class. Replace it with id.

<div id="lapLog"></div> 
Sign up to request clarification or add additional context in comments.

3 Comments

D'oh! Thanks, I should have spotted that.
or use getElementsByClass('lapLog')[0]...
You are right, but for one element it is better to work with id.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.