Adding elements with jquery on html document does not preserve the spacing-margin (bootstrap labels)

StackOverflow https://stackoverflow.com/questions/21864933

Question

I have the following code and is giving me a headacke. I use bootstrap 3.0.3 and jquery 1.11.0. When the code is written in html is written like this.

<td id="td_id">
    <span class="label label-primary">A</span>
    <span class="label label-primary">B</span>
    <span class="label label-primary">C</span>
</td>

and I get a result A B C proper format and margin between the labels. After I press a button, I delete the content of the "td" node and I want to repopulate it again using jquery.

$td = $("#td_id");
$(list).each(function(key, value) {
    var $min_span = $('<span>');
    $min_span.attr("class", "label label-primary");
    $min_span.html(value);
    $td.append($min_span);
});

The elements are added but the problem is that I obtain ABC with no margin(spacing) between the elements. I read on an article that is different if you write the spans on the same line or on different lines. I are written in different line everything is ok.

Does anyone had encountered this? I would attach a picture but I don't have points.. :(

Thanks for the answers

Was it helpful?

Solution

It happens because jQuery append spans without addding any white space between them. Since span is inline element, whitespaces, new lines, etc. cause gaps between them. So you can mimic new line for example:

$td = $("#td_id");
var list = ['A', 'B', 'C'];
$(list).each(function(key, value) {
    var $min_span = $('<span>');
    $min_span.attr("class", "label label-primary");
    $min_span.html(value);
    $td.append($min_span, '\n');
});

Demo: http://jsfiddle.net/u5NAA/

The trick is to insert new line \n, tab \t or even just space ' ' after each span element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top