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

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,这很好。

其他回答

路- [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,这很好。

有一个更简单的方法:

document.getElementsByName('name of metatag')[0].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");
document.querySelector('meta[property="video"]').content

这样你就可以得到元数据的内容。

我的函数变体:

const getMetaValue = (name) => {
  const element = document.querySelector(`meta[name="${name}"]`)
  return element?.getAttribute('content')
}