Is it possible to use jQuery to read meta tags. If so do you know what the basic structure of the code will be, or have links to any tutorials.
6 Answers
Just use something like:
var author = $('meta[name=author]').attr('content');
or this as well
var author = $('meta[name=author]').prop('content');
- 2,955
- 1
- 23
- 19
- 20,290
- 14
- 66
- 90
-
3var author = $("meta[name='author']").attr("content"); The quoting was just a little off. – Jim Speaker Aug 21 '14 at 18:08
-
1@JimSpeaker: technically there is no need for quotes for a single word, though I would agree that it is better to include them regardless. – Qantas 94 Heavy Oct 29 '14 at 02:53
Would this parser help you?
https://github.com/fiann/jquery.ogp
It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:
$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());
Note the single-quotes around the attribute values; this prevents parse errors in jQuery.
- 4,700
- 3
- 9
- 32
- 383
- 2
- 9
-
3the parser you are specifing here ( and in a few more questions ) is for OG DATA ( you even say so yourself ) while the OP was asking about META TAGS and not OG Data. – Rafael Herscovici Dec 05 '11 at 13:31
-
I just tried this, and this could be a jQuery version-specific error, but
$("meta[property=twitter:image]").attr("content");
resulted in the following syntax error for me:
Error: Syntax error, unrecognized expression: meta[property=twitter:image]
Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:
$("meta[property='twitter:image']").attr("content");
(jQuery version 1.8.3 -- sorry, I would have made this a comment to @Danilo, but it won't let me comment yet)
- 1,713
- 2
- 16
- 24
jQuery now supports .data();
, so if you have
<div id='author' data-content='stuff!'>
use
var author = $('#author').data("content"); // author = 'stuff!'
- 588
- 5
- 12
$("meta")
Should give you back an array of elements whose tag name is META and then you can iterate over the collection to pick out whatever attributes of the elements you are interested in.
- 1,326
- 13
- 28
For select twitter meta name , you can add a data attribute.
example :
meta name="twitter:card" data-twitterCard="" content=""
$('[data-twitterCard]').attr('content');
- 4,707
- 14
- 43
- 52
- 21
- 4