22

I wanted to post a code snippet with a meta tag in the document head, so I created a code snippet with a complete HTML document.

Later I saw that Stack Overflow automatically creates an HTML document and my code was put inside that.

Here is an example:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width" />
    </head>
    <body>
        Test!
    </body>
</html>

If you run the code and look inside the source code of the iframe you can see it's rubbish. There are two HTML documents now.

So how can I do it properly?

2

2 Answers 2

34

If dynamically creating the <meta> tag isn't enough, there's a way to put the tag in directly, without JavaScript, through a hack. The text in the CodeMirror textareas will be inserted verbatim into the base HTML markup. For example:

// JavaScript code goes here
/* CSS goes here */
<!-- HTML goes here -->

Right click and Inspect me

Results in:

<!DOCTYPE html>
<html>
<head>
    <style>
        /* CSS goes here */
    </style>
    </head>
<body>
    <!-- HTML goes here -->

Right click and Inspect me
    <script type="text/javascript">
        // JavaScript code goes here
    </script>
</body>
</html>

So, if you put </style> in the CSS section, you'll be in the <head> proper, and you can change it to your heart's content (make sure to start up the <style> again right before the end so that the HTML is valid.) For example:

</style>
<meta name="viewport" content="width=device-width" />
<style>

results in

<!DOCTYPE html>
<html>
<head>
    <style>
        </style>
<meta name="viewport" content="width=device-width" />
<style>
    </style>
    </head>
<body>

    <script type="text/javascript">

    </script>
</body>
</html>
1
  • 5
    This is hideous. People, don't use this. Just write a normal code block instead of a snippet. The extra 10 seconds required for the reader to save your code into a file and then open it in a browser is less than it'll take for them to understand this hack. We got on fine without snippets for years before they got added; a front-end web question not having a snippet is seriously not going to kill anyone. Commented Apr 9, 2019 at 10:49
9

You can add that Meta tag via JavaScript but I'm not sure if that will help for whatever you're trying to fix or demonstrate.

var head = document.getElementsByTagName('head')[0];
var meta = document.createElement('meta');
meta.setAttribute('name',"viewport");
meta.setAttribute('content',"width=device-width");
head.appendChild(meta);
Test!

Here is what you get in the Developer Console of Chrome when you run the snippet:

html in inspector

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.