Jquery function appending to empty div

Viewed 50

I am currently trying to teach myself some coding, and I am following along on a lesson of how to make a stopwatch. So far I have gotten everything to work, except when I hit the lap button it is not taking the laptime and appending it to an empty div. Any ideas?

This is the function I am trying to use:

function addLap(){
    var myLapDetails = "<div>Lap</div>";
    $("#myLapDetails").appendTo("#laps");
}

This is where I am trying to place it:

<div id="laps">

Any thoughts?

2 Answers

You can create a jQuery element from a string and use it like so:

function addLap() {
  var $myLapDetails = $("<div>Lap</div>");
  $myLapDetails.appendTo("#laps");
}

addLap();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="laps"></div>

Note the $ in the variable name is not required but is considered "idiomatic" jQuery if there is such a thing.

Your selector $("#myLapDetails") is looking for an existing element that has id="myLapDetails" that doesn't exist.

You can append the string as variable.

function addLap() {
  var myLapDetails = "<div>Lap</div>";
  $("#laps").append(myLapDetails);
}

addLap();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="laps"></div>

Related