vendredi 10 août 2018

Count the length of elements inside a parent div and put a specific class name according number of childs

I've tried to run an "if" function to add "singleElement" or "multiElement" classes according the number of elements inside to the parent div ("panelContainer"), but the funcion insert the same class to all the parent divs and doesn't count the elements inside to put the according class.

If I execute the "alert(ne)" function it returns separate alerts with the number of "child elements" inside each parent div ("panelContainer"), but the if function doesn't works fine.

What's wrong with my code?

  $('.panelContainer').each(function() {
       var thispanel = $(this);
       var ne = $(thispanel).children('.ReservationMainPanel').length;
       alert(ne);

             if($(ne).length >1){
             $(thispanel).addClass('singleElement');

              }
              else{
               $(thispanel).addClass('multiElement');
             }  

      });

And try with "case" and the same issue, put the same class to all the parent divs in the DOM.

      switch (ne) {
        case (ne >= 2):
            $(thispanel).addClass('multiElement');

            break;

        case (ne === 1):
            $(thispanel).addClass('singleElement');

            break;

        default:
            $(thispanel).addClass('singleElement');
            break;
    }

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire