0

I am trying to loop through multiple lists on a page and depending on the number of items per list, I want to get the height of the each li and set the max height (for 5 items) and set a scrollbar.

I have the following script that goes through each list found and returns the length correctly but I cannot get the height of each li. Thanks for any help.

JQUERY::

        $(".list-item").each(function () {

            var sum = 0;

            var getLength = $(this).children().children().children('ol li').length;
            console.log(getLength);
            //Get length of list items and add scroll bar if more than 5
            if (getLength > 5) {
                $(this).addClass('maxLength');

                $('.maxLength ol li:lt(5)').each(function () {
                    sum += $(this).height();
                    console.log(sum);
                });

                $('.maxLength ol').css({ maxHeight: sum + 'px', overflow: 'auto' });
            }
        });

1 Answer 1

1

Instead of counting children and set height, You can wrap your list in div and add the following css
style:

div{
 max-height:125px(your choice);//The height that 5 li elemtns occupies
 overflow:auto;
 display:inline-block;
}
div li{
 line-height:25px(your choice);
}

Html:

<div>
  <ul> 
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
<div>

I hope this would solve your problem...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rama :) Sadly as there will be multiple lists on an individual page, with the chance of different line heights, I need to loop through and get the heights sadly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.