How can I rewrite this in a simpler way?
$imageContainer = $($(this).parent().children()[0]).children()
currentIdx = 0
for e, idx in $imageContainer
if e.className.indexOf('active')
currentIdx = idx
break
It looks like you're looking for the index of the first child of $imageContainer
with the active
class. (Incidentally, your code will also trigger on stuff like inactive
, which might be a false positive. Be careful about your classes!)
Native selectors work fine here. Furthermore, your initial assignment doesn't do things the jQuery way -- there's no reason to initialise two separate jQuery objects. Try replacing your block with something like:
$imageContainer = $(this).parent().children().first().children()
currentIdx = $imageContainer.index($imageContainer.filter(".active"))
Better yet, instead of that monstrous .parent().children().first().children()
, give it a meaningful ID or class, so you can just do $imageContainer = $(".image-container", this)
.
If you can guarantee that the ul
will contain only li
s, then you can simplify further to currentIdx = $imageContainer.filter(".active").index()
.
Depending on your exact situation, you may even be able to replace everything with the one liner:
currentIdx = $(this).parent().find(".active").index()
$(this)
\$\endgroup\$