[英]TypeScript or JS- How to select an element and all its children into a HTMLCollection?
Updated The code I have come up with is: 更新了我想出的代码是:
<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("*");
I want the collection to include <section>
, <header>
, <p>
, and <div>
the above code only has <header>
, <p>
, and <div>
. 我希望集合包含
<section>
, <header>
, <p>
和<div>
,以上代码仅包含<header>
, <p>
和<div>
。 Is there anyway I can add the <section>
itself to the collection? 无论如何,我可以将
<section>
本身添加到集合中吗?
The problem is that I want to include the element itself into the elements collection. 问题是我想将元素本身包含到elements集合中。 I know I can use outerHTML and put it in a temp container and then get all the element inside from that but i'm looking for a cleaner way.
我知道我可以使用externalHTML并将其放在临时容器中,然后从中获取所有元素,但我正在寻找一种更简洁的方法。
You can use a comma-separated list with querySelectorAll
, where the first item is the element itself. 您可以将带逗号分隔的列表与
querySelectorAll
,其中第一项是元素本身。
This Snippet uses your HTML to retrieve section Test
and its children: header
, p
, and div
: 该代码段使用您的HTML检索
Test
部分及其子项: header
, p
和div
:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.