Skip to content

Commit

Permalink
support DOMTokenList#forEach
Browse files Browse the repository at this point in the history
add forEach method to DOMTokenList
Add a unit test for the new method

fixes #848
  • Loading branch information
mawinter69 authored and rbri committed Aug 13, 2024
1 parent a37d76f commit 26a4c94
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/main/java/org/htmlunit/javascript/host/dom/DOMTokenList.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@
import java.util.HashSet;

import org.apache.commons.lang3.StringUtils;
import org.htmlunit.WebClient;
import org.htmlunit.corejs.javascript.ContextAction;
import org.htmlunit.corejs.javascript.Function;
import org.htmlunit.corejs.javascript.Scriptable;
import org.htmlunit.html.DomAttr;
import org.htmlunit.html.DomElement;
import org.htmlunit.html.DomNode;
import org.htmlunit.javascript.HtmlUnitContextFactory;
import org.htmlunit.javascript.HtmlUnitScriptable;
import org.htmlunit.javascript.JavaScriptEngine;
import org.htmlunit.javascript.configuration.JsxClass;
Expand Down Expand Up @@ -262,6 +266,32 @@ public Object item(final int index) {
return null;
}

/**
* Calls the {@code callback} given in parameter once for each value in the list.
* @param callback function to execute for each element
*/
@JsxFunction
public void forEach(final Object callback) {
final String value = getAttribValue();
if (StringUtils.isEmpty(value)) {
return;
}

final WebClient client = getWindow().getWebWindow().getWebClient();
final HtmlUnitContextFactory cf = client.getJavaScriptEngine().getContextFactory();

final ContextAction<Object> contextAction = cx -> {
final Function function = (Function) callback;
final Scriptable scope = getParentScope();
final String[] values = StringUtils.split(value, WHITESPACE_CHARS);
for (int i = 0; i < values.length; i++) {
function.call(cx, scope, this, new Object[] {values[i], i, this});
}
return null;
};
cf.call(contextAction);
}

/**
* {@inheritDoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,28 @@ public void item() throws Exception {
loadPageVerifyTitle2(html);
}

/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"a", "b", "c", "d", "\u000B", "e", "f", "g"})
public void forEach() throws Exception {
final String html
= "<html><head><script>\n"
+ LOG_TITLE_FUNCTION
+ "function test() {\n"
+ " var list = document.getElementById('d1').classList;\n"
+ " list.forEach((i) => {\n"
+ " log(i);\n"
+ " });\n"
+ "}\n"
+ "</script></head><body onload='test()'>\n"
+ " <div id='d1' class=' a b \t c \n d \u000B e \u000C f \r g'></div>\n"
+ "</body></html>";

loadPageVerifyTitle2(html);
}

/**
* @throws Exception if the test fails
*/
Expand Down

0 comments on commit 26a4c94

Please sign in to comment.