Can’t understand why dynamically html differs from static html. Output seems to be the same when looking in developer tools.
What I want is to have the static html look like dynamically added html, so no spacing between elements.
$(document).ready(function () {
var parentElement = $("#dynamic");
parentElement.html("");
var html = "";
html += "<button>-</i></button>";
html += "<input type='number' value='1' />";
html += "<button>+</button>";
$(html).appendTo(parentElement);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamic">
</div>
<div>
<button>-</button>
<input type='number' value='1' />
<button>+</button>
</div>
>Solution :
You need to inline the tags removing all whitespaces if you do not want any space between the elements
$(function() {
$("#dynamic").html(`<button>-</button><input type="number" value="1" /><button>+</button>`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamic">
</div>
<div><button>-</button><input type="number" value="1" /><button>+</button></div>
Alternatively remove the whitespace around the tags and copy the HTML or clone the existing div content
$(function() {
const $source = $("#source");
const html = $source.html().replace(/\s+(?=<)|(?<=>)\s+/g, '');
$source.html(html)
$("#dynamic").html(html)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamic">
</div>
<div id="source">
<button>-</button>
<input type="number" value="1" />
<button>+</button>
</div>