Wanting to populate a container with a minimum number of children, I’m wondering what the best way of doing this is. For now I got the following, but it’s very bloated… The idea is to have a container that gets populated dynamically. I want the container to always be filled with a minimum of 4 child elements.
for(var k=0; k<parent.length; k++) {
var section = parent[k],
article = parent[k].querySelectorAll('.child');
console.log(article);
if(article.length === 1) {
$('.parent').append('<li class="empty-child"></li><li class="empty-child"></li><li class="empty-child"></li>');
} else if(article.length === 2) {
$('.parent').append('<li class="empty-child"></li><li class="empty-child"></li>');
} else if(article.length < 4) {
$('.parent').append('<li class="empty-child"></li>');
}
}
It just doesn’t feel right to me. I do know I could use .append(new Array…, maybe that’s the way to go?
Any tips would be appreciated.
2
Answers
I got around to test your code the way you intended and I'm happy to say it works like a charm! For those of you out there searching for a similar answer, here's the code:
});
Can use a
for
loop that starts at article length. If the length is already 4 or more it won’t do anything