Can anyone explain why jQuery-attached inline-block elements are losing their space?

So I'm working on a project that involves cloning some objects and adding them to the same parent object and then animating those objects, but my calculations always seemed to be off and I figured it out because the elements in a line box always have an end space that would be nice, but when I add the cloned element using jQuery to the parent div that the trailing space is not included, which leaves things very inconsistent and difficult to work with.

When inspecting elements with browser tools, the elements claim to be identical, setting margins and padding doesn't matter, is this a bug or am I just missing something? Below is a simple demo for replicating the results.

https://jsfiddle.net/kd5opn7j/2/

$('ul').find('li').each(function(){
  $('ul').append($(this).clone());
});

      

li {
  display: inline-block;
  width:50px;
  height:50px;
  background: #555;
}

      

<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

      

+3


source to share


1 answer


The space between boxes comes from new lines and indentation in markup. jQuery does not preserve this formatting style when adding elements, as it modifies the DOM, not the markup directly, and only adds the elements you specify.

In other words, what your markup looks like after jQuery finishes adding new elements:

<ul>
    <li></li>
    <li></li>
    <li></li>
<li></li><li></li><li></li></ul>

      

The inspector displays items in a hierarchical structure for presentation. It does not reflect the actual (or generated) markup.

If you want to preserve whitespace between elements, you can cheat by adding literal space before or after each new element :



$('ul').find('li').each(function(){
  $('ul').append(' ').append($(this).clone());
});

      

Or, if for some reason you absolutely must keep the original indentation style (which will be reflected in the parent innerHTML

) ...

$('ul').find('li').each(function(){
  $('ul').append('    ').append($(this).clone()).append('\n');
});

      

Note that this will have nothing to do with rendering, as all adjacent spaces and newlines will still be condensed to the same space.

+6


source







All Articles