Today I will show you how to style the first word of module or page title like this:
Hello World
CSS doesn’t support this feature until now so we will make it by the help of JavaScript.
Here is the magic code to style the first word of a title
<script type="text/javascript">
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
var j = 0;
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
for (var i = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
//Add span to page title
function addSpanToPageTitle (firstword,el) {
var modules = getElementsByClass (el, null, "div");
if (!modules) return;
for (var i=0; i<modules.length; i++) {
var module = modules[i];
var title = module.getElementsByTagName ("h2")[0];
if (title) {
if (title.getElementsByTagName("span").length == 0) {
text = title.innerHTML;
var pos = text.indexOf(' ');
if (firstword && pos!=-1) {
title.innerHTML = "<span class='pagetitle'>"+text.substr(0,pos)+"</span>"+text.substr(pos);
}else{
title.innerHTML = text;
}
}
}
}
}
//Add span to module title
function addSpanToModuleTitle (firstword,el) {
var modules = getElementsByClass (el, null, "div");
if (!modules) return;
for (var i=0; i<modules.length; i++) {
var module = modules[i];
var title = module.getElementsByTagName ("span")[0];
if (title) {
if (title.getElementsByTagName("span").length == 0) {
text = title.innerHTML;
var pos = text.indexOf(' ');
if (firstword && pos!=-1) {
title.innerHTML = "<span class='modtitle'>"+text.substr(0,pos)+"</span>"+text.substr(pos);
}else{
title.innerHTML = text;
}
}
}
}
}
window.onload = function() {
addSpanToPageTitle('*','contentpaneopen.*');
addSpanToModuleTitle('*','ja-moduletable.*');
};
</script>
the function addSpanToPageTitle for Page title and addSpanToModuleTitle
this code
addSpanToPageTitle('*','contentpaneopen.*');
for page title, JavaScript searches for class “contentpaneopen” when it find it, it searches within that class for tag “h2” as you can see on line 27
var title = module.getElementsByTagName ("h2")[0];
this tag contains Hello World like this
<h2>Hello World</h2>
JavaScript will separate the first word “Hello” and wrapped it with “ span.pagetitle { color: #0000ff; }