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>
. Is there anyway I can add the <section>
itself to the collection?
The problem is that I want to include the element itself into the elements collection. 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.
You can use a comma-separated list with querySelectorAll
, where the first item is the element itself.
This Snippet uses your HTML to retrieve section Test
and its children: header
, p
, and 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.