How to change a CSS style for all elements on a page without having to update each affected element?

I would like to know if there is a way to change a style setting for a page without having to update each affected element?

For example, if I have

<STYLE>
TD.data { font-size: 10pt };
</STYLE>

Open in new window


and I am showing a page with a table with lots of rows and columns with each TD having class="data", then each would have font size of 10 pt. I know that I can find all the elements of tag TD or even found by the selector TD.data, and I know I can change the font size on all of them with a loop in JavaScript.

But is there a way to just find the style
TD.data { font-size: 10pt };

Open in new window

and change it to
TD.data { font-size: 12pt };

Open in new window

, causing the browser to update all the TD.data tags on the page at once?

I can do it now like this:
var myElements = document.getElementsByTagName("TD");
for (var i = 0; i < myElements.length; i++) {
    if (myElements[i].className == 'data') myElements[i].style.fontSize = newFontSize + "pt";
}

Open in new window


but I was hoping there was a faster way.
jkurantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GaryCommented:
Uh?
Just add an inline style block if you only want it to affect one particular page and make sure you place it after any external stylesheets.
0
jkurantAuthor Commented:
I said with JavaScript.
0
GaryCommented:
The easiest way is to add a style block

style = document.createElement('style');
style.appendChild(document.createTextNode('td.data {15px}'));
document.head.appendChild(style);

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Albert Van HalenAnalyst developerCommented:
I played with this idea a while ago and created something.
The idea is simple, it creates a rule in the stylesheet or manipulates an existing one.
After that jquery is used to manipulate the rule via the css method.

The big advantage is imo that newly created elements having a certain class will apply the manipulated rule.

It's been a while since I looked at the code and I'm not quite sure if it's crossbrowser compatible.
It works at least in Chrome, IE11 and Firefox.

Take a look here : http://jsfiddle.net/0g6c0w1e/
0
Julian HansenCommented:
Not sure why you can't use in-page styling to override the style - that is what the scoped attribute is for
<div class="container">
<!-- style will only be applied to td.data elements within the div.container parent -->
<style scoped>
   td.data {font-size: 12pt;}
</style>
<table>
   <tr>
      <td class="data">
      ....
</table>
</div>

Open in new window

Having said that - you can do this with jquery like so
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function() {
    $('td.data').css({fontSize: '12pt'});
});
</script>

Open in new window

0
jkurantAuthor Commented:
Thanks, but I am not familiar with jQuery.

@Gary, I think your solution is going to work, but the whole purpose of this is to give the user some options for text size that they can update instantly on the page (without a server refresh). So, once I have appended the style to the document, how do I get it back to change it? Let's say I set it to 15px but now I want it to be 12px?
0
GaryCommented:
Pop in a function and just pass the fontsize you want to apply

changeFontSize(20);

function changeFontSize(fontsize){
    style = document.createElement('style');
    style.appendChild(document.createTextNode('td.data {'+fontsize+'px}'));
    document.head.appendChild(style);
}

Open in new window

0
jkurantAuthor Commented:
I didn't think that would work because... isn't it adding another style, while there is already a style there?

So,If you have one style

TD.data { font-size: 15pt }

and then added another style

TD.data { font-size: 12pt }

in the same CSS file, one of them would win, right? But I think you are saying that appending a style object to a document replaces any existing style with the same selector? I will give it a try in any case.
0
jkurantAuthor Commented:
That is facinating, about the scoped script tag.
0
GaryCommented:
It is but the new overrides the old one.
0
GaryCommented:
I thought scoped css only works in FF
0
Julian HansenCommented:
@Gary, yes it is, got so used to using it in a dev environment for prototyping forgot it was not supported outside of FF

Thanks, but I am not familiar with jQuery.

@jkurant
All the JQuery you need is in the post.
0
jkurantAuthor Commented:
I still do not have a solution because this did not work:

alert(1);
	style = document.createElement('style');
alert(2);
	node = document.createTextNode('DIV.TableGuidanceWrapperDiv {display: none}');
alert(2.5);
	style.appendChild(node);
alert(3);
	document.head.appendChild(style);

Open in new window


I am using IE8 and it hits an error when it hits appendChild. I get 1, 2, and 2.5. Then it stops.

What I am trying to do is make the DIV with class=TableGuidanceWrapperDiv  disappear.
0
GaryCommented:
Fixed

changeFontSize(20);

function changeFontSize(fontsize){
	head = document.head || document.getElementsByTagName('head')[0];
	style = document.createElement('style');
	style.type="text/css";
	if (style.styleSheet){
		style.styleSheet.cssText ="td.data{font-size:"+fontsize+"px}";
	}
	else{
		style.appendChild(document.createTextNode("td.data{font-size:"+fontsize+"px}"));
	}
	head.appendChild(style);
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jkurantAuthor Commented:
I am starting to believe that the answer to my question is that it is impossible. It seems that if you want to change the style of elements, you have to use a loop to iterate through elements changing the ones that need to be changed. It does not appear that there is any way to do it "all at once".

If I don't get any clarifications soon, I will close the question and award points.
0
GaryCommented:
The above code does it, styles are applied autmotically, there is no looping.
0
Albert Van HalenAnalyst developerCommented:
as Gary stated his technique is working. You just have to wrap it into a solid function.
As for my solution, if you know how to use jquery it's even more easier because the logic itself is taken care of by jquery. You just have to use the existing css method.

So: it is working; just choose the answer which suits your needs.

As for your comment "I'm not familiar with jquery" : you do webdevelopment right?
0
jkurantAuthor Commented:
First I must defend my skills since you asked if I was a web developer.
I have done "web development" with Lotus Notes Domino for about 10 years, but I admit that is hardly a standard tool. I have built sites using HTML and lots of JavaScript and a little CSS. I have written some rather sophisticated functionality using JavaScript but I just have never used jquery. It wasn't available in any of the tools I have ever used, and it isn't now, to my knowledge. I started in the past year working in WebSphere at the bank where I work. For my private work I have just set up a Linux hosting account with tomcat and GlassFish, so I can start building websites, but I am not familiar with GlassFish.  I am not sure what GlassFish adds to Tomcat with JSPs and servlets.

Now, regarding the answers. Somehow I did not notice Gary's second chunk of code, so I will implement that on Monday and find out if it works. I'm guessing it will because it would address the condition where the style already exists.

Albert, I just don't understand your code at http://jsfiddle.net/0g6c0w1e/. It looks a lot like JavaScript but I don't know $ is. Is that JQuery? I think I will read up on JQuery before Monday.
0
GaryCommented:
Jquery is just a javascript library that makes writing javascript far easier, it's nothing more or less than javascript itself
Instead of doing this
document.getElementById("someid").value

you just do
$("#someid").val()

...and the jquery just uses plain js to give you the result, same as any language - if you do something often enough you just write a function to return you the result.
Of course there is a lot more to jquery then just a simple selector engine.

Simple example
http://jsfiddle.net/t3bh64f1/
0
Albert Van HalenAnalyst developerCommented:
Yes $ is shorthand for jquery.
If you really do more with development, I'd consider using jquery.

Additional note to Gary's comment: jquery is more than that. It's also a library which abstracts away all the different browser implementations on how to handle certain things. I.e. in Gary's example with the if statement : if this than that or else.
0
Julian HansenCommented:
Also regarding the comment you made that your tools do not include JQuery.

JQuery is implemented by adding a single line of code to your page

<script src="http://code.jquery.com/jquery.js"></script>

Open in new window

You can also download the JQuery library and run it from your web file system.
To start using it you do as follows
<script type="text/javascript">
// This is equivalent to the window.onload
// i.e anything in the function block will
// be executed when the document is ready
$(function() {
 // JQuery / javascript here
});
</script>
As the other two experts have pointed out JQuery makes working with the DOM a lot easier, handles cross platform integration and adds rich features that would require many hours of development and testing using plain JS.
If you add the JQuery library above and then this line of code anywhere after - you should get the results you are after.
<script type="text/javascript">
$(function() {
    $('td.data').css({fontSize: '12pt'});
});
</script>

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
CSS

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.