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

javascript - Change or swap the CSS of multiple HTML elements at once - Stack Overflow

programmeradmin0浏览0评论

I have about 100 <span class="foo">, 100 <span class="bar"> and 100 <span class="baz"> tags in my document. I need to implement the following operations in JavaScript:

  • Change the background all foos to red, all bars to green, all bazes to blue.
  • Change the background all foos to green, all bars to blue, all bazes to red.
  • Change the background all foos to blue, all bars to red, all bazes to green.

I will call these operations about 1000 times altogether, so I'd like to avoid a solution which appends a <style> tag to the <head> each time I do an operation.

Is there something simpler or faster or better than iterating over all <span> elements with document.getElementsByTagName('span'), and changing or appending to the .className DOM properties for each element?

I have about 100 <span class="foo">, 100 <span class="bar"> and 100 <span class="baz"> tags in my document. I need to implement the following operations in JavaScript:

  • Change the background all foos to red, all bars to green, all bazes to blue.
  • Change the background all foos to green, all bars to blue, all bazes to red.
  • Change the background all foos to blue, all bars to red, all bazes to green.

I will call these operations about 1000 times altogether, so I'd like to avoid a solution which appends a <style> tag to the <head> each time I do an operation.

Is there something simpler or faster or better than iterating over all <span> elements with document.getElementsByTagName('span'), and changing or appending to the .className DOM properties for each element?

Share Improve this question edited Feb 21, 2010 at 17:14 kat asked Feb 21, 2010 at 15:04 katkat 2,0754 gold badges16 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

The simplest way is to use CSS to do this, rather than changing the element classnames. Consider the following markup and CSS.

.normal .foo{
    background-color: #0f0;
}
.alternate .foo {
    background-color: #f00;
}

<body class="normal">
    <span class="foo">hello</span>
    <span class="bar">hello</span>
    <span class="baz">hello</span>
</body>

You can simply use javascript to change the classname on the body from normal to alternate, to implement the color change on .foo elements. More rules will set colors for bar and baz.

document.getElementsByTagName('body')[0].className = 'alternate';

You could give the body of your document a class to determine which configuration of colours should be used and then simply style the spans accordingly.

eg:

.configTypeOne span.foo{...}
.configTypeTwo span.foo{...}

If you're then changing the styles on the same page after some period of time, a small piece of JS to change the class of the body will be all that's required.

发布评论

评论列表(0)

  1. 暂无评论