我的 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/