如何在JS或jQuery循环中移除子DOM元素类?代码问题排查
The issue here is that your jQuery collection childElms is static—it doesn’t update automatically when the elements’ classes change. Let’s break down exactly what’s happening step by step:
- When you run
var childElms = parentElm.find('a');, you create a jQuery object containing all four<a>elements from the initial DOM state. This collection stays fixed even after you modify the elements (like removing their class). - Your loop runs 4 times, but every iteration calls
childElms.last(), which always targets the fourth element (Link4) from the original collection. - First iteration: Link4’s
ancclass is removed successfully. - Iterations 2–4:
childElms.last()still points to Link4, but it no longer has theancclass—soremoveClass('anc')does nothing.
How to Fix It
Option 1: Remove the Class from All Elements (Simplest)
If your goal is to remove the anc class from every <a> element, you don’t need a loop at all. jQuery’s removeClass works on entire collections directly:
childElms.removeClass('anc');
Option 2: Remove Classes Starting from the Last (If You Need the Loop Behavior)
If you specifically want to process elements from last to first (maybe for animation or other custom logic), you have two solid approaches:
Approach A: Re-select Elements with the Class Each Time
This ensures you always target the current last element that still has the anc class:
var total = childElms.length; for(var i=0;i<total;i++) { parentElm.find('a.anc').last().removeClass('anc'); }
Approach B: Iterate Backwards Through the Original Collection
Since you already have all elements in childElms, you can loop from the last index to the first and remove the class from each:
var total = childElms.length; for(var i = total - 1; i >= 0; i--) { $(childElms[i]).removeClass('anc'); }
Either of these will remove the anc class from all four elements as expected.
内容的提问来源于stack exchange,提问作者Parashuram

