lycan1385 lycan1385 - 2 months ago 19
HTML Question

Adding text to a dynamically created DOM element

I'm trying to create

<div>
elements with child
<p>
elements; the
<div>
elements are being assigned a class of "clock" + a number (increments). While the elements themselves seem to be created, adding text (in my case a moment object) to the
<p>
element doesn't work.

HTML:

<body>
<select class="tz_list" name="timezones">
<option value="default">Please Select a Timezone</option>
</select>
<input type="button" name="addClock" value="Add Clock" class="button">
</body>


JS:

$(document).ready(function () {
var now = moment();
console.log(now);
//var repeat = setInterval(displayTime, 200);
var tzones = moment.tz.names();
tzones.forEach(function(key,value){
$('<option/>').val(key).html(key).appendTo('.tz_list');
});
var repeat;
var clock_count = 1;
var timezone ="";


function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock '+clock_number.toString() + ' p';
console.log(selector);
//$('.clock '+clock_number.toString()).css({"height":"100px", "width":"500px"});
$(selector).text(location.toString());
};

$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock '+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);

});

$('.tz_list').on('change', function(event){
console.log(event.target.value);
timezone = event.target.value;

});

});


What am I missing?
Here is a JSFiddle

Answer Source

Instead creating class "clock " try to create with out giving space. It will work.

    function displayTime(timezone, clock_number) {
   console.log(timezone);
   var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
   console.log(location);
   //$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
   var selector = '.clock'+clock_number.toString() + ' p';
   console.log(selector);
   //$('.clock'+clock_number.toString()).css({"height":"100px", "width":"500px"});
   $('.clock'+clock_number.toString()).text(timezone);
   $(selector).text(location.toString());
 };
$('.button').on('click', function(e){
   console.log(e.target.value);
   var div = '<div class="clock'+clock_count.toString()+'"><p></p></div>';
   $(div).insertAfter('.button');
   clock_count+=1;
   displayTime(timezone, clock_count-1);

});