-2
\$\begingroup\$

I'm still learning jQuery and am wondering if there are other ways to put .each() inside another .each() function:

JavaScript:

$("ul").each(function(index){

    $("#uid" + index + " li").each(function(listItemIndex){

        var listItemWidth = $(this).width();
        var listItemPosition = listItemIndex * listItemWidth;

        if (listItemIndex > 0){
            $(this).css("left", listItemPosition + (10 * listItemIndex));
        };
    });

});

HTML:

<ul id="uid0">
    <li>
        Lorem ipsum dolor sit amet
    </li>
    <li>
        Lorem ipsum dolor sit amet
    </li>
</ul>
<ul id="uid1">
    <li>
        Lorem ipsum dolor sit amet
    </li>
</ul>
<ul id="uid2">
    <li>
        Lorem ipsum dolor sit amet
    </li>
    <li>
        Lorem ipsum dolor sit amet
    </li>
    <li>
        Lorem ipsum dolor sit amet
    </li>
    <li>
        Lorem ipsum dolor sit amet
    </li>
</ul>
\$\endgroup\$
-2
\$\begingroup\$
$("ul").each(function() {
    var ul = this;
    $(ul).children('li').each(function(listItemIndex) {
        if (listItemIndex > 0) {
            var listItemWidth = $(this).width();
            var listItemPosition = listItemIndex * (listItemWidth + 10);
            $(this).css("left", listItemPosition);
        };
    });
});
\$\endgroup\$
  • \$\begingroup\$ (Yes, I know it's over 2 years old now, doesn't matter). Code-only answers are generally not good because they do not explain how or why they improve upon the OP's code. Even a short explanation of what your solution does and why would be far better than no explanation at all. \$\endgroup\$ – Kaz Jan 5 '16 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.