I would like the result instead of outputting in console.log to output in several DIV or SPAN for example ---div Id="div1">result one------div Id="div2">result two-- ----div Id="div3">result three----div Id="div4">result four---
here I leave the code in js
function Obtenerhorariosdesdemedicos(){
const Horario = {
dia: {
inicio: 8,
fin: 13
},
tarde: {
inicio: 16,
fin: 20
},
cada: 15,
};
var now = new Date();
var inicial = new Date(now.getFullYear(), now.getMonth(),
now.getDay(), Horario.dia.inicio, 0, 0, 0);
var final = new Date(now.getFullYear(), now.getMonth(), now.getDay(),
Horario.dia.fin, 0, 0, 0);
for (var f = inicial; f <= final; f.setMinutes(f.getMinutes() +
Horario.cada))
{
let hora = ("0" + String(f.getHours())).slice(-2); //slice para dar
formato de 2 digitos
let minutos = ("0" + String(f.getMinutes())).slice(-2);
console.log(hora + ":" + minutos );
}
}
You would need to have a previously identified container to which you will later add the elements once created. I have created this element in the HTML:
<div id="resultados"></div>
and I will use it to put in it the different elements that are created.I'll show you a safe and optimized way to do it.
Regarding security , you will certainly find code that would add the content using things like
innerHTML
, which is not secure , due to the risks of code injection, that's why I created the elements withcreateElement()
and set their attributes and their content with functions dedicated to those purposes.Regarding optimization, the web is full of bad examples in which, for cases like these, they suggest adding each element to the
div
container within the same loop, which is not optimal , because it is not convenient to modify the DOM within loops. That's why I've used a snippet, added everything to that snippet inside the loop, and finally added that snippet to the containing div once the loop is done, so the DOM will only change once. This is the most optimal way, because every time you modify the DOM, it is rendered . If your loop hasN
elements and you modify the DOMN
times, it means that the DOM will be renderedN
times and that can end up being very expensive.Let's see the code. I have put comments so that it is better understood. I have used an element
p
because it seemed the most appropriate. But you can change it for aspan
, for adiv
or whatever you want. In that case, I advise you to manage the spaces between lines through style rules in a file.css
, thus applying the principle of separation of responsibilities.If there is something you have not understood, you can tell me in a comment, at the bottom of this answer. I hope it helps you.