javascript - 从没有名称的元素中选择属性

标签 javascript

我的 HTML 中有这个

<meta name="title" content="Hello World"/>
<meta property="article:published_time" content="2014-11-20T11:00:01+00:00"/>

我想访问文章:published_time 内容数据。

在控制台中,这是有效的: document.getElementsByTagName("meta")['title']

但是我无法获取“article:publish”

document.getElementsByTagName("meta")['article:published_time']

显示为未定义。我尝试用“\\”转义

最佳答案

document.getElementsByTagName返回 HTMLCollection 。可以使用 ['xyz'] 表示法来访问集合的元素,但这将查找 id 为 'xyz' 的元素,或者如果失败,则查找名称为 'xyz' 的元素。集合的元素也可以通过整数索引访问,如下所示。

您的第一个示例之所以有效,是因为您有一个名称为“title”的元元素。但你的第二个例子没有名称或 ID。所以你必须循环遍历集合:

var pub_time, collection = document.getElementsByTagName("meta");
for(var i = 0;i < collection.length;i++) {
  if(collection[i].getAttribute("property") === "article:published_time") {
   pub_time = collection[i].getAttribute("content");
}

有关 HTMLCollection 的更多信息,请参见此处:https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

关于javascript - 从没有名称的元素中选择属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956563/

相关文章:

javascript - 如何从 D3 中的矩形获取数据?

javascript - 需要 child div 成为 parent ,但在 js 或 css 中有可能吗?

javascript - 如何在点击元素时触发网页的谷歌翻译?

javascript - 使用 RequireJS 找不到 Backbone Marionette 依赖项

javascript - 来自关联数组的树

javascript - 使用 SPServices 获取选择列选项

javascript - jQuery : how to hide div after animation?

javascript - 传单:layer.getLatLng 不适用于 .eachLayer 函数

javascript - 在 Node 中高效地逐行读取文件

javascript - 使用javascript在不使用循环的情况下搜索对象中的数组