Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top