Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble using jQuery to set meta tag values [duplicate]

Possible Duplicate:
Is it possible to use javascript to change the meta-tags of the page?

I'm trying to set meta tags using jQuery (please don't reply that this doesn't make sense since search engines blah-blah-blah... I am loading invoking 3rd party Javascript functions that examine these vales, such as Tweetmeme and Facebook).

If I use:

 $('meta[name=some-name]').attr('content', 'some value');

it does work to set the value of an existing meta tag, but does not create a meta tag if such a named one does not exist.

If you have insight or experience with this, please reply...

like image 760
Zhami Avatar asked May 14 '10 02:05

Zhami


People also ask

How to replace DOM element JQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.

What is a meta tag Javascript?

The <meta> tag defines metadata about an HTML document. Metadata is data (information) about data. <meta> tags always go inside the <head> element, and are typically used to specify character set, page description, keywords, author of the document, and viewport settings.


1 Answers

You can do this, not the cleanest, but what you're trying to do is pretty odd so there's not a great way to handle it:

var mt = $('meta[name=some-name]');
mt = mt.length ? mt : $('<meta name="some-name" />').appendTo('head');
mt.attr('content', 'some value');

The conditional expression in there checks .length, which is 0 or false if not found, if that's the case we create the element and append it to the head, whether it was added or originally found, mt is set to the <meta> with that name now, and you can set the attribute.

like image 113
Nick Craver Avatar answered Oct 12 '22 11:10

Nick Craver