View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.html;
16  
17  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import org.htmlunit.html.DomElement;
23  import org.htmlunit.html.DomNode;
24  import org.htmlunit.html.HtmlLabel;
25  import org.htmlunit.javascript.host.dom.NodeList;
26  
27  /**
28   * A special {@link NodeList} to implement {@code .labels} property.
29   *
30   * @author Ahmed Ashour
31   * @author Ronald Brill
32   */
33  class LabelsNodeList extends NodeList {
34  
35      /**
36       * Creates an instance.
37       *
38       * @param domeNode the {@link DomNode}
39       */
40      LabelsNodeList(final DomElement domeNode) {
41          super(domeNode, false);
42      }
43  
44      /**
45       * This is overridden in order to prevent caching at all.
46       *
47       * {@inheritDoc}
48       */
49      @Override
50      public List<DomNode> getElements() {
51          final List<DomNode> response = new ArrayList<>();
52          final DomElement domElement = (DomElement) getDomNodeOrDie();
53          for (DomNode parent = domElement.getParentNode(); parent != null; parent = parent.getParentNode()) {
54              if (parent instanceof HtmlLabel) {
55                  response.add(parent);
56              }
57          }
58          final String id = domElement.getId();
59          if (ATTRIBUTE_NOT_DEFINED != id) {
60              for (final DomElement label : domElement.getHtmlPageOrNull().getElementsByTagName("label")) {
61                  if (id.equals(label.getAttributeDirect("for"))) {
62                      response.add(label);
63                  }
64              }
65          }
66  
67          return response;
68      }
69  }