如何获取嵌套子元素的属性

尼玛加达

我想从嵌套的子节点内部检索特定的属性值。做这个的最好方式是什么?

下面的代码有效,但我不会每次都知道子节点的数量。

 parent.childNodes[0].childNodes[0].childNodes[0].getAttribute('placeholder');
福斯·罗德里格斯

您可以使用递归函数解决此问题。
我做了这个来解决这个问题。

function getNestedAttribute(node, attrib) {
  // this is not really eficient but I forced it to use childnodes
  if (node.childNodes.length && node.children.length) {
    node.childNodes.forEach((child) => {
     if (child.nodeName === "#text") return;
       return getNestedAttribute(child, attrib);
      });
    }
    else {
      let attr = node.getAttribute(attrib) || null;
      if (!attr) return;
      console.log(`[${attrib}]`, attr, {
        info: {
          node,
          attrib,
        },
      });
    }
}

在这里你有一个有效的解决方案=)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Recursive Placeholder</title>
  </head>
  <body>
    <ul id="parent">
      <li>
        <ul>
          <li><input type="text" placeholder="hi there" /></li>
          <li><input type="text" placeholder="hola" /></li>
        </ul>
      </li>
    </ul>

    <button type="button" onclick="getPlaceholder()">Get Placeholder</button>
    <div>
      <div>
        <div>
          <div>
            <button type="button" onclick="getAllTypes()">Get Types</button>
          </div>
        </div>
      </div>
    </div>

    <script>
      function getPlaceholder() {
        const parent = document.getElementById("parent");
        getNestedAttribute(parent, "placeholder");
      }

      function getNestedAttribute(node, attrib) {
        if (node.childNodes.length && node.children.length) {
          node.childNodes.forEach((child) => {
            if (child.nodeName === "#text") return;
            return getNestedAttribute(child, attrib);
          });
        } else {
          let attr = node.getAttribute(attrib) || null;
          if (!attr) return;
          console.log(`[${attrib}]`, attr, {
            info: {
              node,
              attrib,
            },
          });
        }
      }

      // Extra:
      function getAllTypes() {
        getNestedAttribute(document.body, "type");
      }
    </script>
  </body>
</html>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章