Javascript add class and keep original

Im using the following:

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

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

However, the problem with this method is that the class only gets the application that no longer has the assigned class.

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

 <body class="originalClass filenameClass"> ... </body> 
+4
source share
4 answers

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

+1
source

You do not need to replace the class, just add it like this:

 document.body.className += " " + fname 

You might want to do some checking though for everything that comes through querystring ...

+10
source

According to specifications

classList returns a bullet list of the element's class attribute.

So you can do:

 document.body.classList.add(fname); 

and it will work just like the jQuery addClass method. Only adding a class once and saving existing classes.

You can also do:

 document.body.classList.remove(fname); 

if you want to delete the class later

toggles and contains methods also available initially

+4
source

document.body.className+=" "+fname

+3
source

All Articles