我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
当前回答
document.head.querySelector(“元[属性=视频]”).content;
其他回答
你可以用这个:
function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('video'));
将所有元值复制到缓存对象:
/* <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);
在Jquery中,你可以实现这一点:
$("meta[property='video']");
在JavaScript中,你可以通过以下方法实现:
document.getElementsByTagName('meta').item(property='video');
路- [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,这很好。
如果您对获得所有元标记的更深远的解决方案感兴趣,可以使用这段代码
function getAllMetas() {
var metas = document.getElementsByTagName('meta');
var summary = [];
Array.from(metas)
.forEach((meta) => {
var tempsum = {};
var attributes = meta.getAttributeNames();
attributes.forEach(function(attribute) {
tempsum[attribute] = meta.getAttribute(attribute);
});
summary.push(tempsum);
});
return summary;
}
// usage
console.log(getAllMetas());