TypeScript 或 JS- 如何将一个元素及其所有子元素 select 放入 HTMLCollection 中?

TypeScript or JS- How to select an element and all its children into a HTMLCollection?

已更新 我想出的代码是:

<section id="Test">
   <header>Welcome</header>
   <p>This is a test</p>
   <div>Nothing here</div>
</section>

var element =  document.getElementById("Test");
var elements = <HTMLCollection>element.getElementsByTagName("*");

我要合集包括<section>,<header>,<p>,<div>以上代码只有<header>,<p>,以及 <div>。无论如何我可以将 <section> 本身添加到集合中吗?

问题是我想将元素本身包含到元素集合中。我知道我可以使用 outerHTML 并将其放入临时容器中,然后从中获取所有元素,但我正在寻找一种更简洁的方法。

您可以在 querySelectorAll 中使用逗号分隔的列表,其中第一项是元素本身。

此代码段使用您的 HTML 检索部分 Test 及其子部分:headerpdiv

var elements= document.querySelectorAll('#Test, #Test *');
console.log(elements.length); //4
<section id="Test">
   <header>Welcome</header>
   <p>This is a test</p>
   <div>Nothing here</div>
</section>