I’m using $.each to iterate through an object and I’m struggling to add a thematic break after every 7th property:value.
$.each(element, function (key, value) { $("#result1").append(key + ": " + value + "<br>"); });
I’m using the above code and I’m able to display each property:value on a new line on the browser, but just can’t figure out how to add the thematic break. Is it even possible?
Any suggestions would be most welcomed.
Advertisement
Answer
You’ll need to track the index, or implement a counter as I have here, and use the modulus (remainder) operator %
to insert a break on the interval you want.
The remainder operator (%) returns the remainder left over when one operand is divided by a second operand.
const element = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'}; let i = 0; $.each(element, function (key, value) { if (i%7 === 0) $("#result1").append("<hr />"); $("#result1").append(key + ": " + value +"<br>"); i++; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="result1"></div>
Or using plain js…
const element = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'}; let result = document.getElementById('result1'); Object.entries(element).forEach(([key, value], i) => { if (i%7 === 0) result.innerHTML += '<hr />'; result.innerHTML += `${key}: ${value} <br>`; });
<div id="result1"></div>