Reputation: 51
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
Upvotes: 1
Views: 173
Reputation: 38190
You almost guessed it right ;-)
function doSomethingWithAllPres() {
var pres = document.getElementsByTagName("pre");
for (var i = 0; i < pres.length; i++) {
// you can check the class name via pres[i].className === "highlight"
// (and you should use a class instead of an id therefore)
if (pres[i].className.indexOf("highlight") >= 0) {
// action goes here
}
}
}
Using a JS-Framework like jQuery, things would be even more simple:
$("pre.highlight").each(function(i) {
// action goes here
});
However, using a framework might be overkill...
Upvotes: 2