View Javadoc
1   /*
2    * Copyright (c) 2002-2025 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   */
34  class LabelsNodeList extends NodeList {
35  
36      /**
37       * Creates an instance.
38       *
39       * @param domeNode the {@link DomNode}
40       */
41      LabelsNodeList(final DomElement domeNode) {
42          super(domeNode, false);
43      }
44  
45      /**
46       * This is overridden in order to prevent caching at all.
47       * <p>
48       * {@inheritDoc}
49       */
50      @Override
51      public List<DomNode> getElements() {
52          final List<DomNode> response = new ArrayList<>();
53          final DomElement domElement = (DomElement) getDomNodeOrDie();
54          for (DomNode parent = domElement.getParentNode(); parent != null; parent = parent.getParentNode()) {
55              if (parent instanceof HtmlLabel) {
56                  response.add(parent);
57              }
58          }
59          final String id = domElement.getId();
60          if (ATTRIBUTE_NOT_DEFINED != id) {
61              for (final DomElement label : domElement.getHtmlPageOrNull().getElementsByTagName("label")) {
62                  if (id.equals(label.getAttributeDirect("for"))) {
63                      response.add(label);
64                  }
65              }
66          }
67  
68          return response;
69      }
70  }