Issue
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='2' />
<button>+</button>
</div>
Solution
MDN will tell you How is whitespace handled
So let's try a zero width font inspired by this answer to How to remove the space between inline/inline-block elements?)
$(function() {
$("#dynamic").html(`<button>-</button><input type="number" value="1" /><button>+</button>`)
});
@import url('https://cdn.jsdelivr.net/font-zero-width/latest/zero-width.css');
.zerowidth {
font-family: 'zero-width';
font-size: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamic" class="zerowidth">
</div>
<div class="zerowidth">
<button>-</button>
<input type="number" value="1" />
<button>+</button>
</div>
If you do not want to do it using a font, then 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>
Answered By - mplungjan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.