Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert metatag without using jquery append?

I used the following jquery to insert a metatag into a html document.

<script type="text/javascript">
if(screen.width>=320 && screen.width<=767){
$('head').append('<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">');}    
</script>

If possible, I'd like to insert the metatag without using jquery. Anyone have any ideas how I can do that?

I believe I will probably need to use document.getElementByTagName but I'm not sure how.

Just in case you are wondering, I am inserting the metatag into my html to to optomize the site for viewing with the iphone. Unfortunately, width=device-width is not an option as it doesn't play well with my ipad version.

like image 938
TryHarder Avatar asked Oct 10 '11 10:10

TryHarder


People also ask

How to add meta tag dynamically using javascript?

You can add it: var meta = document. createElement('meta'); meta. httpEquiv = "X-UA-Compatible"; meta.

How to prepend Element in jQuery?

The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.

How to append an Element as a first child in jQuery?

The . prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).


2 Answers

var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=320, initial-scale=1.0, maximum-scale=1.0, user-scalable=0";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);
like image 117
Kai Avatar answered Nov 15 '22 23:11

Kai


You can also use "setAttribute" (rather than the "dot" notation) for weirdo attribute names (that contain non-alpha-numeric characters).

Example:

var iefix=document.createElement('meta');
iefix.setAttribute("http-equiv", "X-UA-Compatible");
iefix.setAttribute("content", "IE=Edge");
document.getElementsByTagName('head')[0].appendChild(iefix);

The example above causes IE (<=9) to always use the latest document standards mode. Sometimes IE will fall back to older standards, and therefore break your modern javascript / canvas web app.

like image 45
bob Avatar answered Nov 16 '22 00:11

bob