views:

1569

answers:

4

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

$(document).ready(function() {
$("code").wrapInner("<pre></pre>");
});

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

alert($("code").html());

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?

+1  A: 

Are you using the latest jQuery ? What if you try

$("code").wrapInner(document.createElement("pre"));

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

Pat
+3  A: 

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

Pat
+7  A: 

That's the difference between block and inline elements. pre is a block level element. It's not legal to put it inside a code tag, which 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 white-space: pre, but apparently IE 6 only honors that in Strict Mode.
markpasc
Use of the code tag could be excused as being much more semantic - not that it makes it correct.
nickf
+1  A: 

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.

Vincent Robert