pistacchio
pistacchio

Reputation: 58963

jQuery: Getting the "raw" content of an element

I have this div:

<div id="test">
    {{? a && b || c < 0}}
        <div>Pece &alt; Love!</div>
    {{?}}
</div>

I neet do get its content just like it's reported above (che curly braces syntax is for a template engine).

Unfortunately, neither .html() nor .text() work:

// $('#test').text() 
{{? a && b || c < 0}}
    Pece &alt; Love!
{{?}}

.text() gets rid of tags

// $('#test').html()
{{? a &amp;&amp; b || c &lt; 0 }}
    <div>Pece &amp;alt; Love!</div>
{{?}}

.html() encodes the ampersands (and < >).

Any help? Thanks

Upvotes: 0

Views: 388

Answers (1)

Blender
Blender

Reputation: 298582

It's not a good idea to store your templates as HTML. Store them inside of <script> tags with a custom mimetype:

<script type="text/your-template" id="template">
    {{? a<b && b>c }}
        <div>Peace &amp; Love!</div>
    {{?}}
</script>

Storing templates that aren't HTML as HTML will yield undesirable results, as you've noticed:

  • Your original markup is gone. What you see when you look at the .innerHTML property is what the browser interpreted your template to be if it was valid HTML, which can change it: http://jsfiddle.net/ZFd6a/3/
  • a<b && b>c will turn into ac, as the middle portion will be interpreted as an element.
  • Stray lesser-than and greater-than signs will be turned into character entities.
  • You have to use HTML character entities.

You're entirely at the mercy of the browser's HTML parser. When you move your template into <script> tags with a mimetype that isn't reserved for JavaScript, your template is treated as a string, which is exactly what you want.

Upvotes: 8

Related Questions