Viewed 7344 times

I'm trying to use jQuery to format code blocks, specifically to add a <pre> tag inside the <code> tag:

$(document).ready(function() {

Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert


I see that IE has inserted some additional text into the pre tag:

<PRE jQuery1218834632572="null">

If I reload the page, the number following jQuery changes.

If I use wrap() instead of wrapInner(), to wrap the <pre> outside the <code> tag, both IE and Firefox handle it correctly. But shouldn't <pre> work inside <code> as well?

I'd prefer to use wrapInner() because I can then add a CSS class to the <pre> tag to handle all formatting, but if I use wrap(), I have to put page formatting CSS in the <pre> tag and text/font formatting in the <code> tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.

Has anyone else encountered this? Am I missing something?

5 answers given for "How do I add a pre tag inside a code tag with jQuery?"

Accepted Solution

That's the difference between can only contain inline content.

Because browsers have to support whatever godawful tag soup they might find on the real web, Firefox tries to do what you mean. IE happens to handle it differently, which is fine by the spec; behavior in that case is unspecified, because it should never happen.

  • Could you instead replace the code element with the pre? (Because of the block/inline issue, technically that should only work if the elements are inside an element with "flow" content, but the browsers might do what you want anyway.)
  • Why is it a code element in the first place, if you want pre's behavior?
  • You could also give the code element pre's whitespace preserving power with the CSS IE 6 only honors that in Strict Mode.

Btw I don't know if it is related but pre tags inside code tags will not validate in strict mode.

Are you using the latest jQuery ? What if you try


Is it any better or do you get the same result ?

As markpasc stated, a PRE element inside CODE element is not allowed in HTML. The best solution is to change your HTML code to use <pre><code> (which means a preformatted block that contains code) directly in your HTML for code blocks.

You could use html() to wrap it:

    var self = $(e);
    self.html('<pre>' + self.html() + '</pre>');

As mentioned above, you'd be better off changing your html. But this solution should work.