diff --git a/HTMLKit/HTMLParser.m b/HTMLKit/HTMLParser.m
index a94a4ef..230ad53 100644
--- a/HTMLKit/HTMLParser.m
+++ b/HTMLKit/HTMLParser.m
@@ -588,20 +588,29 @@
HTMLElement *lastNode = furthestBlock;
NSUInteger index = [_stackOfOpenElements indexOfElement:node];
- for (int innerLoopCounter = 0; innerLoopCounter < 3; innerLoopCounter ++) {
- index--;
+ int innerLoopCounter = 0;
+ while (YES) {
+
+ innerLoopCounter += 1;
+ index -= 1;
+
node = _stackOfOpenElements[index];
+ if ([node isEqual:formattingElement]) {
+ break;
+ }
+
+ if (innerLoopCounter > 3 && [_listOfActiveFormattingElements containsElement:node]) {
+ [_listOfActiveFormattingElements removeElement:node];
+ continue;
+ }
+
if (![_listOfActiveFormattingElements containsElement:node]) {
[_stackOfOpenElements removeElement:node];
continue;
}
- if ([node isEqual:formattingElement]) {
- break;
- }
-
HTMLElement *newElement = [node copy];
[_listOfActiveFormattingElements replaceElementAtIndex:[_listOfActiveFormattingElements indexOfElement:node]
withElement:newElement];