Skip to content

Commit 380bf3e

Browse files
committed
Implement Document.getElementById() without using xpath
1 parent 2114290 commit 380bf3e

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/main/java/org/htmlunit/javascript/host/dom/Document.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3519,9 +3519,10 @@ public HTMLCollection getAll() {
35193519
@JsxFunction
35203520
public HtmlUnitScriptable getElementById(final String id) {
35213521
final DomNode domNode = getDomNodeOrDie();
3522-
final Object domElement = domNode.getFirstByXPath("//*[@id = \"" + id + "\"]");
3523-
if (domElement != null) {
3524-
return ((DomElement) domElement).getScriptableObject();
3522+
for (final DomElement descendant : domNode.getDomElementDescendants()) {
3523+
if (descendant instanceof HtmlElement && id.equals(((HtmlElement) descendant).getId())) {
3524+
return descendant.getScriptableObject();
3525+
}
35253526
}
35263527
return null;
35273528
}

src/test/java/org/htmlunit/javascript/host/dom/Document2Test.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,32 @@ public void getElementById() throws Exception {
496496
loadPageVerifyTitle2(html);
497497
}
498498

499+
500+
/**
501+
* @throws Exception if the test fails
502+
*/
503+
@Test
504+
@Alerts({"zero", "udef"})
505+
public void getElementByIdNull() throws Exception {
506+
final String html
507+
= "<html><head>\n"
508+
+ "<script>\n"
509+
+ LOG_TITLE_FUNCTION
510+
+ "function doTest() {\n"
511+
+ " log(top.document.getElementById(null).name);\n"
512+
+ " log(top.document.getElementById(undefined).name);\n"
513+
+ "}\n"
514+
+ "</script></head>\n"
515+
+ "<body onload='doTest()'>\n"
516+
+ "<form id='form1'>\n"
517+
+ "<input id='undefined' name='udef' type='text' value='u' />\n"
518+
+ "<input id='null' name='zero' type='text' value='n' />\n"
519+
+ "</form>\n"
520+
+ "</body></html>";
521+
522+
loadPageVerifyTitle2(html);
523+
}
524+
499525
/**
500526
* @throws Exception if the test fails
501527
*/

0 commit comments

Comments
 (0)