我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?

HTML:

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

当前回答

将所有元值复制到缓存对象:

/* <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);

其他回答

如果元标签是:

<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" />'
<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

复杂网站和元数据的问题是元标签并不总是有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') );
      }
  }
function getMetaContentByName(name,content){
   var content = (content==null)?'content':content;
   return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}

以这种方式使用:

getMetaContentByName("video");

本页上的例子:

getMetaContentByName("twitter:domain");

供参考,根据https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta全局属性是有效的,这意味着id属性可以与getElementById一起使用。