Roooooo
Roooooo

Reputation: 172

Using javascript to highlight syntax in code examples.

So, I was looking how to do something similar to Stackoverflow's code thing:

e.g. The "var" is colored and "test" isn't

var test

How would I write a JavaScript function to do this?

This is what I tried

if ("var")  {
document.getElementByTagName("code").style.color="purple";
}

So when the text "var" is in a "code" element, it turns JUST "var" purple.

Upvotes: 2

Views: 124

Answers (3)

ElvinD
ElvinD

Reputation: 695

HTML and js element

 <div>
   var test;
 </div>


<script>
 var varText = $( "div" ).text().split( " " ).join( "</span> <span>" );
 newText = "<span>" + varText + "</span>";

$( "div" )
.html( varText )
.find( "span" )
.end()
.find( ":contains('var')" )
.css({
  "color": "purple",

});

Upvotes: 0

Mike Lyons
Mike Lyons

Reputation: 1792

I would wrap the variable name in a span

<code>
  var <span class="variable-name">test</span>
</code>

Then color just the span, jQuery makes this easier

$('code span.variable-name').css('color', 'purple');

However, There are also syntax highlighting libraries that would make this whole thing easier since it's largely a solved problem :) Here is an example

Upvotes: 2

mVChr
mVChr

Reputation: 50205

Here's a quick and dirty (emphasis on dirty) way to do it with regex replace if:

  1. You don't care about actually parsing the syntax
  2. You know the code elements only contain clean text, no child tags

If that's so, you can do something like:

var els = document.getElementsByTagName('code'),
    code;

for (var i = 0; i < els.length; i++) {
    code = els[i].innerHTML;
    els[i].innerHTML = code.replace(
        /\bvar\b/g,
        '<span style="color: #f00;">var</span>'
    );
}

Yes, it's better practice to use a class instead of inline style, but seeing as not following the above two points is also bad practice, this is just for example's sake.

See demo

Upvotes: 0

Related Questions