在DOM中查找所有需要的标签[关闭]

问题描述 投票:-1回答:1

我需要一个搜索函数,该函数需要一个“ document”和“ tagname”作为输入,并返回与该标签相对应的所有元素的数组。不使用“ getElementsByTagName”和jquery怎么办?

文档示例:

<head>
  <title>Hello, World</title>
</head>
<body>
  New

  <div>
   <h1>Start</h1>
   <div>
    <h2>Continue</h2>
   </div>
  </div>

  <p>Paragraph</p>

  <table>
   <tr>
    <th>1</th>
    <th>2</th>
   </tr>
   <tr>
    <td>
     <ul>
      <li>li</li>
      <li>li</li>
      <li>li</li>
     </ul>
    </td>
    <td>
     <p>Paragraph 2</p>
    </td>
   </tr>
  </table>

  <ul>
   <li>li</li>
  </ul>

</body>

如果我这样做:

 const el = document.documentElement.childNodes;

我只有“头”和“身体”元素。如何获取数组中的所有dom元素?所有“ li”和“ td”等等。

它应该如何工作:

const elements = search(document, 'p'); // ['<p>1</p>' '<p>2</p>']
console.log(elements.length); // 2

const elements = search(document, 'td'); // ['<td>1</td>' '<td>2</td>']
console.log(elements.length); // 2

有人可以帮忙吗?或提供建议我如何获取数组中的所有dom元素

javascript html dom
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.