0

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.

DonO
  • 1,030
  • 1
  • 13
  • 27
  • *" include the element itself"* - not sure I get what you're asking... – tymeJV Mar 11 '15 at 15:26
  • You're going to have to include more information, and some HTML code, if you want us to understand what you are trying to do. – Dave Mar 11 '15 at 15:26
  • The node you get from `getElementById()` will retain its `childNodes` / `children `; so... Just retrieve that one node and access its children directly when you need to? – David Thomas Mar 11 '15 at 15:27
  • 1
    related: http://stackoverflow.com/questions/8856281/how-to-add-an-element-into-the-htmlcollection-in-javascript – epascarello Mar 11 '15 at 15:28

1 Answers1

3

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>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
  • Thank you! This is what I am looking for except I want it to be a little more universal. So it can work with any tag dynamically. In this case you know it is a UL tag. Lets pretend we don't know what tag the element is. in other words in a function where the element is passed in how can I get the element itself and its children into a html collection. – DonO Mar 11 '15 at 15:43
  • I've updated my answer. To use `querySelectorAll` with an id, prepend a pound sign to the id. – Rick Hitchcock Mar 11 '15 at 15:45