我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
当前回答
路- [1]
function getMetaContent(property, name){
return document.head.querySelector("["+property+"="+name+"]").content;
}
console.log(getMetaContent('name', 'csrf-token'));
你可能会得到错误: 无法读取属性“getAttribute”为空
路- [2]
function getMetaContent(name){
return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));
你可能会得到错误: 无法读取属性“getAttribute”为空
路- [3]
function getMetaContent(name){
name = document.getElementsByTagName('meta')[name];
if(name != undefined){
name = name.getAttribute("content");
if(name != undefined){
return name;
}
}
return null;
}
console.log(getMetaContent('csrf-token'));
而不是得到error,得到null,这很好。
其他回答
其他答案应该可以做到这一点,但这一个更简单,不需要jQuery:
document.head.querySelector("[property~=video][content]").content;
最初的问题使用了带有property=""属性的RDFa标记。对于正常的HTML <meta name=""…>标签,您可以使用如下内容:
document.querySelector('meta[name="description"]').content
document.querySelector('meta[property="video"]').content
这样你就可以得到元数据的内容。
使用元根,然后获取和设置它的任何属性:
let meta = document.getElementsByTagName('meta')
console.log(meta.video.content)
> "http://video.com/video33353.mp4"
meta.video.content = "https://www.example.com/newlink"
复杂网站和元数据的问题是元标签并不总是有itemprop属性。在某些情况下,它们只有itemprop而没有name属性。
使用这个脚本,您可以获得带有itemprop属性的所有元数据并打印其内容。
const allMeta = document.getElementsByTagName("meta");
for (let i = 0; i < allMeta .length; i++) {
if( allMeta [i].getAttribute("itemprop") != null){
console.log( allMeta [i].getAttribute("itemprop")+":"+allMeta [i].getAttribute('content') );
}
}
最简单的方式
我们可以直接使用一行来获得标题部分的元描述或关键字或任何元标记,如下所示:
document.head.getElementsByTagName('meta')['description'].getAttribute('content');
只需将['description']更改为关键字或元名称rang的元素
这是一个例子: 使用文档。获取元名称值