0

Assuming the html below:

<div id="contentWrapper">
  <h2>Title<br>Page</h2>
  <div>
  <h4>Subtitle Text<br>
  March 26, 2018</h4>
  <p><iframe src="https://www.youtube.com/embed/ID" allow="autoplay" allowfullscreen="" width="760" height="428" frameborder="0"></iframe></p>
  </div>
  <p>This is text that adds meaningful value to the website. It is what the user reads</p>
  <p>If you have read up to this part I'm actually impressed.</p>
  <p><strong>* * * * * * *</strong></p>
</div>

How can I get every immediate child tag within the contentWrapper as an array that would look like this:

[h2, div, p, p, p]

Notice I don't want the children of children, just the first child.

I thought about using the querySelectorAll() method, but from what I can tell this requires a css selector as a parameter. I won't know ahead of time what types of tags are in this div so I can't "pre-feed" it selectors.

3 Answers 3

2
  Array.from( document.getElementById("contentWrapper").children, el => el.tagName)

getElementById()

.children

Array.from

Sign up to request clarification or add additional context in comments.

Comments

1

Use Array.from and Array.map

let el = Array.from(document.querySelectorAll("#contentWrapper > *")).map(a => a.tagName);
console.log(el);
<div id="contentWrapper">
  <h2>Title<br>Page</h2>
  <div>
  <h4>Subtitle Text<br>
  March 26, 2018</h4>
  <p><iframe src="https://www.youtube.com/embed/ID" allow="autoplay" allowfullscreen="" width="760" height="428" frameborder="0"></iframe></p>
  </div>
  <p>This is text that adds meaningful value to the website. It is what the user reads</p>
  <p>If you have read up to this part I'm actually impressed.</p>
  <p><strong>* * * * * * *</strong></p>
</div>

Comments

1

If you want a nodelist of the child elements:

document.querySelector('#contentWrapper').children;

If you want an array of the child element names:

[...document.querySelector('#contentWrapper').children].map(el => el.tagName)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.