Call JSON.stringify on all pre elements

788 views Asked by At

I'm trying to JSON.stringify all JSON text in <pre> elements in a document with a specified class, and then use google-code-prettify to add syntax colouring. Since I don't know Javascript or jQuery I'm struggling - so far all I have is the following:

<body onload="prettyPrint()">
    ...
    <pre class="prettyprint lang-js">{...}</pre>
    ...
</body>
<script>
    $('[class="prettyprint lang-js"]').next().text("TEST"); // call JSON.stringify()?
</script>

The pretty-printing works, but I don't know how to call JSON.stringify or even just select the correct elements.

More specifically, what I want to do is for all <pre> elements in the document with the "prettyprint lang-js" class, I'd like to replace the text content with the results of calling JSON.stringify on that text, and then call
google-code-prettify `prettyPrint()' to syntax colour it.

1

There are 1 answers

1
ShankarSangoli On BEST ANSWER

You can use class selector to select any element by a class name. Try this.

$('.prettyprint.lang-js').each(function(){
    var $this = $(this);
    $this.text(JSON.stringify($this.text()));
});

//Now you can call prettyPrint
prettyPrint();