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:
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?
By calling element. style. color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id .
When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.
The HTML class attribute is used to specify a class for an HTML element. Multiple HTML elements can share the same class.
You can force the content of the HTML <div> element stay on the same line by using a little CSS. Use the overflow property, as well as the white-space property set to “nowrap”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With