首页 > 解决方案 > Gain access to child elements under HTMLCollection's

问题描述

How do you gain access to child elements under HTMLCollection's children?

My code returns the following at: console.log(iframeContent);. I want to gain access to the children highlighted below and loop through/interrogate them.

enter image description here

Full code below:

function getPageStructure() {
  const iframe = document.getElementById('builder-showcase');
  const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
  const iframeContent = iframeDocument.getElementsByTagName('body')[0].children;
  console.log(iframeContent);
}

Have tried the following:

console.log(iframeContent.children);
console.log(iframeContent[0].children);

but getting an undefined error message on both.

标签: javascript

解决方案


const iframeContent = iframeDocument.getElementsByTagName('body')[0].children;

已经抓住了.children,所以日志记录console.log(iframeContent.children);不起作用。

改为使用console.log(iframeContent)

如果console.log(iframeContent)获取包含子项的数组,则可以使用console.log(iframeContent[0]),反之亦然,以选择其中的div元素iframeContent

您还可以使用iframeContent.forEach(child => console.log(child))记录iframeContent.


推荐阅读