I have the following DOM structure:
<div id="module-main">
<div id="module-crumbs">
<h4>Hello</h4>
</div>
</div>
When I place that in a document and view it, it works fine. But if I build it from jQuery like so:
$('#module-main').append($('<div id=\"module-crumbs\" />'));
$('#module-crumbs').append($('<h4/>').html('Hello'));
Instead of the H4 margins expanding within “module-crumbs” it’ll expand just beyond “module-main” … what is most confounding is that the DOM structure is exactly the same after jQuery runs. How does the browser calculate the margins and why does it matter if I do it through Javascript vs hand coding it if the results are the same? Any ideas?
Thanks!
Edit: While I marked the best answer as it re-wrote what I was doing in a much more readable manner, the real root cause of the problem ended up being collapsing margins that did not trigger with jQuery because the jQuery was calling module-crumb instead of module-crumbs and there was nothing to prevent the border from collapsing. Putting a 1px padding brought it together (a border would have worked as well).
The DOM resulting from the markup and that generated by jQuery is not the same – the html() method is not behaving as you expect it to.
The H4 element in the initial markup contains only a single text node.
To build the same DOM with jQuery, use:
For a more markup-like representation (which can often be easier to read), try: