【问题标题】:Loop through a collection of HTML elements in an iframe [duplicate]循环遍历 iframe 中的 HTML 元素集合 [重复]
【发布时间】:2019-10-30 09:47:30
【问题描述】:

我想遍历 iframe 中的一组 HTML 元素并找出一组元素在屏幕上出现的顺序,然后在其后面创建一个新列表。

我在const tempPageStructure = builderShowcase.frameElement.contentDocument["all"]; 获得 iframe div。

目前,我想不通,如何检索上面看到的元素标签名称,运行下面的脚本在console.log(tempPageStructure[i].name);返回null。

const activeComponents = ['app-builder-navbar', 'app-builder-hero', 'app-builder-placeholder'];
const builderShowcase = $(builderShowcaseId).get(0).contentWindow;

function getPageStructure() {
  const tempPageStructure = builderShowcase.frameElement.contentDocument["all"];
  let pageStructure = [];
  for(let i = 0; i < tempPageStructure.length; i++) {
    console.log(tempPageStructure[i].name);
    for(let j = 0; j < activeComponents.length; j++) {
      if(tempPageStructure[i].name === activeComponents[j]) {
        pageStructure.push(tempPageStructure[i])
      }
    }
  }
  console.log(tempPageStructure);
  console.log(pageStructure);
  return pageStructure;
}

【问题讨论】:

  • 你不是在找el.name,而是在找el.tagNamelet tagNames = []; for (const element of document.all) { tagNames.push(element.tagName.toLowerCase()); } console.log(JSON.stringify(tagNames));
  • @connexo 如何与$(builderShowcaseId).get(0).contentWindow一起使用它

标签: javascript


【解决方案1】:

tempPageStructure.name 替换为tempPageStructure.tagName

const activeComponents = ['app-builder-navbar', 'app-builder-hero', 'app-builder-placeholder'];
const builderShowcase = $(builderShowcaseId).get(0).contentWindow;

function getPageStructure() {
  const tempPageStructure = builderShowcase.frameElement.contentDocument["all"];
  let pageStructure = [];
  for(let i = 0; i < tempPageStructure.length; i++) {
    console.log(tempPageStructure[i].tagName);
    for(let j = 0; j < activeComponents.length; j++) {
      if(tempPageStructure[i].tagName === activeComponents[j]) {
        pageStructure.push(tempPageStructure[i])
      }
    }
  }
  console.log(tempPageStructure);
  console.log(pageStructure);
  return pageStructure;
}

【讨论】:

  • 不需要 querySelector,OP 已经通过可用的 (document.all) 实现了这一点。
  • 谢谢,我该如何使用$(builderShowcaseId).get(0).contentWindow。我想以独占方式访问 iframe 窗口中的 HTML 内容。
  • @connexo 这是不推荐使用的方法developer.mozilla.org/ru/docs/Web/API/Document/all
  • @methuselah 在这种情况下,您使用的是 el.name 您应该使用 el.tagName
  • 您能否更新答案以显示它的外观?
猜你喜欢
  • 2022-11-20
  • 2021-07-31
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
相关资源
最近更新 更多