admin管理员组

文章数量:1315033

I want to check a meta tag exist on webpage.

I have tried this :

document.getElementsByTagName("meta[http-equiv:Content-Type]").length

But this alway return 0. How can I do that? I want to do it by using javascript. Not jQuery.

I want to check a meta tag exist on webpage.

I have tried this :

document.getElementsByTagName("meta[http-equiv:Content-Type]").length

But this alway return 0. How can I do that? I want to do it by using javascript. Not jQuery.

Share Improve this question asked Jan 27, 2014 at 18:56 CoolCool 3482 gold badges11 silver badges32 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 9
var x = document.querySelector('meta[http-equiv="Content-Type"]');
console.log(x);

x has a reference to the meta tag if found. It will be null otherwise, so you can use if (x) {

Live demo (click).

Here's a way to do it if querySelectorAll isn't supported (older browsers)

var metas = document.getElementsByTagName('meta');

var found;
for (var i=0; i<metas.length; ++i) {
  var meta = metas[i];
  if (meta.getAttribute('http-equiv') === "Content-Type") {
    found = meta;
    break;
  }
}

console.log(found);

Live demo (click).

found has a reference to the meta tag if it existed. You could do if (found) { to determine whether or not it exists.

本文标签: htmlCheck meta tag exist on webpage using javascriptStack Overflow