Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a pre tag inside a code tag with jQuery?

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?

like image 313
Bruce Alderman Avatar asked Aug 15 '08 21:08

Bruce Alderman


2 Answers

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.
like image 148
markpasc Avatar answered Sep 18 '22 21:09

markpasc


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

like image 30
Pat Avatar answered Sep 19 '22 21:09

Pat