HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Cleanup code to add div structure to element

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cleanupdivstructureelementcodeadd

Problem

I was cleaning up my code when I came across this situation :

var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var count = 1;
var html = '';
for (var i = 0; i ';
    var cell = '';
    cell += '' + a[i] + '';
    cell += '';
    var rowEnd = '';

    if (count == 1) {
        html += rowStart + cell;
        count++;
    } else if (count == 3) {
        html += cell + rowEnd;
        count = 1;
    } else {
        html += cell;
        count++
    }
}
$('#container').append(html);


jsFiddle

I retrieve data from a database which I want to display in a div structure as shown above. This code however looks ugly and I think it can be way shorter, I just don't know how.

I was hoping someone could give me some advice/methods/anything on how to clean up this code.

Solution

You should let CSS handle most of the job for you. Example

JS:

var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var count = 1;
var html = '';
for (var i = 0; i " + a[i] + "");
    $('#container').append(div);
}


CSS (where the magic is):

#container div:nth-child(3n+1) { / Every third! /
clear: both;
}

#container div {
float: left;
width: 100px;
}

Code Snippets

var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var count = 1;
var html = '';
for (var i = 0; i < a.length; i++) {
    var div = $("<div>" + a[i] + "</div>");
    $('#container').append(div);
}

Context

StackExchange Code Review Q#53876, answer score: 7

Revisions (0)

No revisions yet.