最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript add class and keep original - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question asked Jan 9, 2010 at 22:49 CLiownCLiown 13.8k50 gold badges127 silver badges205 bronze badges 4
  • Just curious; why don't you use jQuery? – Danny Roberts Commented Jan 9, 2010 at 22:52
  • How can I do this with jQuery? – CLiown Commented Jan 9, 2010 at 22:57
  • 1 @danit: $('body').addClass(fname); – Christian C. Salvadó 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??? – Ariel Commented Jan 10, 2010 at 1:39
Add a comment  | 

4 Answers 4

Reset to default 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...

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

document.body.className+=" "+fname

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

发布评论

评论列表(0)

  1. 暂无评论