Search code examples
javascriptjqueryhtmlmeta

Return Meta Tag as String


I am trying to return this meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1">

So when the mobile page is displayed you will see that tag on the page.

How do I return a tag and the contents of the tag?


Solution

  • You can grab the meta element and put a clone of it in a memory div, and then take the html of that, to finally display that as text somewhere in your document:

    $('#output').text($('<div>').append($('meta[name=viewport]').clone()).html());
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="output"></div>

    Alternative based on outerHTML

    This is more straightforward: take the outer HTML of the meta tag and output it:

    $('#output').text($('meta[name=viewport]').prop('outerHTML'));
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="output"></div>