Simply tag-based highlighting with Javascript

Posted by nkd on Stack Overflow See other posts from Stack Overflow or by nkd
Published on 2010-03-16T22:06:32Z Indexed on 2010/03/16 22:11 UTC
Read the original article Hit count: 167

Filed under:
|

Hello,

I got this code which works:

    <html>

    <head>

    <title>JS highlighting test</title>

    <script type="text/javascript">

    function highlight()
    {
            var t = document.getElementById('highlight').innerHTML;

            t = t.replace(/(if|switch|for|while)\s*(\()/gi, "<b>$1</b>$2");
            document.getElementById('highlight').innerHTML = t;
    }

    </script>

    </head>

    <body onload="javascript:highlight();">

    <pre id="highlight">
    1  if(foo) {
    2          bar();
    3  }
    4
    3  while(--baz) {
    5          oof();
    6  }
    </pre>

    </body>

    </html>

I would like to have it for all <pre> tags instead of just one with some specific and unique id as it works now. The best would be to have an combination of a specific tag with a specific id. Is it possible to extend the small JS function above to work this way (using some document.getElementsByTag(tag).getElementsById(id).innerHTML or something alike (I don't know what exactly suites the need) in a loop? I tried myself but with no real success. I need only as simple solution as possible, nothing really special.

Thank you for your ideas.

--
nkd

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about AJAX