Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically added html vs static html differs

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How is whitespace handled

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading