【问题标题】:How to access html element text in chrome devtools console如何在 chrome devtools 控制台中访问 html 元素文本
【发布时间】:2018-01-23 00:40:31
【问题描述】:

我有一个包含一大堆blackquote 标签的页面。 在开发控制台中,我输入document.getElementsByTagName("blockquote"),它给了我一个数组。

但是如果我这样做document.getElementsByTagName("blockquote").innerText document.getElementsByTagName("blockquote").innerHTML document.getElementsByTagName("blockquote").textContent document.getElementsByTagName("blockquote").outerTextdocument.getElementsByTagName("blockquote").outerHTML

全部返回undefined

但是,如果我检查数组 document.getElementsByTagName("blockquote") 的元素,我可以看到上述所有属性。

如何访问其中至少一个(innerTextouterHTLMinnerTextouterHTMLtextContent)?

【问题讨论】:

  • $$('blockquote').map(e=>e.textContent)
  • @wOxxOm 如果我使用的是jQuery,这可能是一个很好的答案
  • 另外,jQuery 没有 $$
  • 另一个有用的提示:您可以将代码保存在“源”面板中的 sn-p 中,以便以后轻松运行。

标签: html google-chrome-devtools


【解决方案1】:

或者,如果您想访问任何特定元素,您可以使用数组中的索引

for (var i=0; i <document.getElementsByTagName("blockquote").length; i++ ){
    var singleElement = document.getElementsByTagName("blockquote")[i];
    console.log(singleElement.innerHTML);
}

【讨论】:

    【解决方案2】:

    您需要迭代数组才能访问这些属性。像这样的东西对他们有用:

    var elements = document.getElementsByTagName("blockquote");
    
    for (var prop in elements)
    {
      if(elements.hasOwnProperty(prop)) {
        console.log(elements[prop].innerHTML);
      }
    }

    【讨论】:

    • 是的,我不确定 .inner* 是否适用于每个元素。你说的都是有道理的。
    • 是的,这些属性适用于单个元素。所以你需要做的就是从数组中获取这些元素。你甚至可以为第一个元素使用document.getElementsByTagName("blockquote")[0].innerHTML
    • 刚刚这样做document.getElementsByTagName("blockquote").forEach(function(elem) { console.log(elem.innerHTML);}); - forEach is not a function - 我认为这是jQuery 方式,因为我没有在页面上,收到错误。
    • 我的错!您需要使用属性访问元素。 for(var prop in document.getElementsByTagName("blockquote")) 会为此工作。让我也更新一下我的答案。
    • 为什么访问prop而不是像@user4906240这样的元素循环更好?
    【解决方案3】:

    你也可以试试下面的命令:

    var elements = document.getElementsByTagName("blockquote");。这将返回元素列表。访问 i 索引处所需元素的文本 elements[i].value.

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 2014-04-25
      • 2013-05-23
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多