如何使用JavaScript从元标记中获取信息?

241

我需要的信息在一个meta标签中。当property="video"时,我如何访问meta标签中"content"数据?

HTML:

<meta property="video" content="http://video.com/video33353.mp4" />

5
请注意,<meta> 标签应该有一个 name 属性,而不是 property 属性。使用标准属性的开发者需要根据大多数答案提供的代码进行调整。 - Jens Bannmann
25个回答

0

0
使用原生JavaScript非常简单...
var author = document.querySelector("meta[name=author]").content;
alert(`My author is ${author}`);

-1
<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>

演示


-2

document.head.querySelector('meta[property=video]').content;


1
为了符合Stackoverflow网站的要求,您的回答需要更加完整,尽量减少关于代码的解释。 - Antonio Leonardo

-3
如果 meta 标签是:
<meta name="url" content="www.google.com" />

JQuery 将会是:

const url = $('meta[name="url"]').attr('content'); // url = 'www.google.com'

JavaScript将是:(它将返回整个HTML)

const metaHtml = document.getElementsByTagName('meta').url // metaHtml = '<meta name="url" content="www.google.com" />'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接