我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
当前回答
这里有一行
document.querySelector("meta[property='og:image']").getAttribute("content");
其他回答
function getDescription() {
var info = document.getElementsByTagName('meta');
return [].filter.call(info, function (val) {
if(val.name === 'description') return val;
})[0].content;
}
版本更新:
function getDesc() {
var desc = document.head.querySelector('meta[name=description]');
return desc ? desc.content : undefined;
}
我的函数变体:
const getMetaValue = (name) => {
const element = document.querySelector(`meta[name="${name}"]`)
return element?.getAttribute('content')
}
function getMetaContentByName(name,content){
var content = (content==null)?'content':content;
return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}
以这种方式使用:
getMetaContentByName("video");
本页上的例子:
getMetaContentByName("twitter:domain");
<html>
<head>
<meta property="video" content="http://video.com/video33353.mp4" />
<meta name="video" content="http://video.com/video33353.mp4" />
</head>
<body>
<script>
var meta = document.getElementsByTagName("meta");
size = meta.length;
for(var i=0; i<size; i++) {
if (meta[i].getAttribute("property") === "video") {
alert(meta[i].getAttribute("content"));
}
}
meta = document.getElementsByTagName("meta")["video"].getAttribute("content");
alert(meta);
</script>
</body>
</html>
Demo
将所有元值复制到缓存对象:
/* <meta name="video" content="some-video"> */
const meta = Array.from(document.querySelectorAll('meta[name]')).reduce((acc, meta) => (
Object.assign(acc, { [meta.name]: meta.content })), {});
console.log(meta.video);