trobbins26
trobbins26

Reputation: 219

Create classes for body tag using javascript

I have multiple pages that need consistent <body> classes, plus a unique class per page. I would like to set these values dynamically to eliminate managing constant classes on page level.

The ideal solution would start with an empty <body> tag, where the javascript created will allow me to inject classes when needed. The potential properties are

tabClass, catClass, secClass, pageClass

Where any combination of these can exist, including none at all. Can anyone help me with this? I am at the beginning stages of learning Javascript so I apologize now for my ignorance. Thanks.

The ideal output would be:

bodyClasses = (tabClass, catClass, secClass)
pageClass = (pageClass)

Upvotes: 0

Views: 244

Answers (2)

RobG
RobG

Reputation: 147413

Seems like you need some functions like:

var util = util || {};

util.trim = function(s) {
  return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}

util.dom = util.dom || {};

util.dom.hasClassName = function(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);

    var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
    return el && re.test(el.className);
}

util.dom.addClassName = function(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (!util.dom.hasClassName(el, cName)) {
        el.className = util.trim(el.className + ' ' + cName);
    }
}

util.dom.addClassNames = function(el) {

    if (typeof el == 'string') el = document.getElementById(el);

    for (var i=1, iLen=arguments.length; i<iLen; i++) {
      util.dom.addClassName(el, arguments[i]);
    }
}

util.dom.removeClassName = function(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (util.dom.hasClassName(el, cName)) {
        var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
        el.className = util.trim(el.className.replace(re, ''));
    }
}

And use them like:

var body = document.body;
util.dom.addClassName(body, 'tabClass');

The addClassNames function takes multiple arguments:

util.dom.addClassNames(body, 'tabClass', 'catClass', 'secClass');

Note that if the element already has the class, it isn't added a second time.

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150040

In a script element somewhere after the opening <body> tag:

var commonClasses = "tabClass catClass secClass",
    currentPageClasses;

/* Your own logic here to determine what classes apply to the
   current page, add them to currentPageClasses variable */

document.getElementsByTagName("body")[0].className += " "
                                                   + commonClasses
                                                   + " "
                                                   + currentPageClasses;

Demo: http://jsfiddle.net/nnnnnn/FhMP8/

Upvotes: 2

Related Questions