美文网首页
children&childNodes获取dom所有子节点

children&childNodes获取dom所有子节点

作者: Wrestle_Mania | 来源:发表于2021-05-28 11:35 被阅读0次
<template>
  <div class="wrapper" id="wrapper">
    <h1>1212121</h1>
    <h2>1212121212</h2>
    <div class="">
      <div class="">
        <div class="">121212</div>
      </div>
    </div>

    <span>121212</span>
  </div>
</template>
  • childNodes
<script>
export default {
  mounted() {
    const arr = getAllNodes(document.getElementById("wrapper"));
    console.log(arr);

    function getAllNodes(dom) {
      const doms = [];
      const { childNodes } = dom;
      [...childNodes].map((item) => {
        const { nodeType } = item;
        if (nodeType === 1) {
          doms.push(item, ...getAllNodes(item));
        }
      });
      return doms;
    }
  },
};
</script>
  • children
<script>
export default {
  mounted() {
    const arr = getAllNodes(document.getElementById("wrapper"));
    console.log(arr);

    function getAllNodes(dom) {
      const doms = [];
      const { children } = dom;
      [...children].map((item) => {
        doms.push(item, ...getAllNodes(item));
      });
      return doms;
    }
  },
};
</script>

相关文章

网友评论

      本文标题:children&childNodes获取dom所有子节点

      本文链接:https://www.haomeiwen.com/subject/rgcssltx.html