skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    jQuery(document).ready(function($) {
    
    $('.section').each(function() {
        var child = $(this).find('li');
    
        for(var i=child.length; i<4; i++) {
            $(this).append('<li>empty</li>');
        }
    });
    

    });


  2. Can use a for loop that starts at article length. If the length is already 4 or more it won’t do anything

    var $parent =  $('.parent')
    for(var j = article.length; j< 4; j++){
        $parent.append('<li class="empty-child"></li>');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search