5

Im using the following:

url=location.href
fname=url.match(/.*\/(.*)\./)[1]
document.body.className=fname

This takes part of the URL and adds a class to the <body> tag with the text extracted from the URL.

However the problem with this method is the class only gets applied providing doesnt already have a class assigned.

Im really looking for something similar to the JQUERY .addClass function so body becomes:

<body class="originalClass filenameClass">

...

</body>
4
  • Just curious; why don't you use jQuery? Commented Jan 9, 2010 at 22:52
  • How can I do this with jQuery? Commented Jan 9, 2010 at 22:57
  • 1
    @danit: $('body').addClass(fname); Commented Jan 9, 2010 at 23:00
  • 1
    @danit, why did you say similar to jquery .addClass() and then ask if jquery can do it??? Commented Jan 10, 2010 at 1:39

4 Answers 4

10

You don't have to replace the class, just append to it like this:

document.body.className += " " + fname

You may want to run some validation though on everything that arrives via querystring...

Sign up to request clarification or add additional context in comments.

Comments

6

According to the specs

classList returns a token list of the class attribute of the element.

So you can do:

document.body.classList.add(fname);

and it will work just like jQuery's addClass method. Only adding the class once and keeping existing classes.

You can also do:

document.body.classList.remove(fname);

if you'd like to remove the class later

toggle and contains methods are also available natively

Comments

3

document.body.className+=" "+fname

Comments

1

With JQuery you can do $("body.className").addClass(fname) or similarly without JQuery you can do document.body.className += " " + fname

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.