假设下面的html:
<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>
如何获取contentWrapper中的每个直接子标签为数组,如下所示:
[h2, div, p, p, p]
请注意,我不需要孩子的孩子,只是第一个孩子。
我考虑过使用querySelectorAll()方法,但是据我所知,这需要一个css选择器作为参数。我不会提前知道此div中的标签类型,因此无法“预送”它的选择器。
答案 0 :(得分:2)
Array.from( document.getElementById("contentWrapper").children, el => el.tagName)
答案 1 :(得分:1)
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>
答案 2 :(得分:1)
如果要子元素的节点列表:
document.querySelector('#contentWrapper').children;
如果需要子元素名称的数组:
[...document.querySelector('#contentWrapper').children].map(el => el.tagName)