Reputation: 4729
I'm using highlight.js to show code on my website. Now I would like to make some parts of the highlighted code to links. But the link is not processed and represented as code.
This is how my code is highlighted:
<xml attribute="value">My <a href="test.html">xml content</a> that should be clickable (link)</xml>
But I would like to have this, and the word content as a link:
<xml attribute="value">My content that should be clickable (link)</xml>
I use the highlight.js like specified in the documentation like this:
<script src="highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<pre><code id="myCode"><xml attribute="value">My <a href="test.html">content</a> that should be clickable (link)</xml></code></pre>
How can I use links inside the highlighted xml code?
INFORMATION! I found out that the problem only occurs because I'm changing the content with an ajax call where I receive a JSON containing the whole code:
$.ajax({
url: 'GetCode',
data: {id: id},
dataType: 'json',
type: 'get',
cache: false,
success: function(node) {
$("#myCode").text(node.code);
$('#myCode').each(function(i, e) {
hljs.highlightBlock(e)
});
}
Upvotes: 4
Views: 2050
Reputation: 4592
I think the problem with your current code is that it's using jquery's $(obj).text()
instead of $(obj).html()
. .text()
simply escapes any text by creating a textNode and appending that. This is handy for showing user-submitted data. But this does mean that your links will be shown as code instead of HTML.
For that, we need to use HTML, but then, it won't show the XML tags anyway as the browser thinks it could be an HTML tag. So what we need is to escape the XML tags, but then leave the anchors/links as html code. So something like
var code= var code='XMLCODEHERE' //let's say this is data from ajax return
var escapedCode=code.replace(/</g,"<") //rough escaping of code
//rough unescaping of anchors
var escapedCodeNotAnchor=escapedCode.replace(/<a /g,"<a ")
escapedCodeNotAnchor=escapedCodeNotAnchor.replace(/<\/a>/g,"</a>")
$("#myCode").html(escapedCodeNotAnchor) //instead of .(text)
Upvotes: 3