Solved

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

Posted on 2014-10-13
21
253 Views
Last Modified: 2014-10-22
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.
0
Comment
Question by:jkurant
  • 8
  • 7
  • 3
  • +1
21 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 40378643
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
 

Author Comment

by:jkurant
ID: 40378691
I said with JavaScript.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40378713
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
 
LVL 19

Expert Comment

by:Albert Van Halen
ID: 40379340
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40380208
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
 

Author Comment

by:jkurant
ID: 40380391
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
 
LVL 58

Expert Comment

by:Gary
ID: 40380492
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
 

Author Comment

by:jkurant
ID: 40380591
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
 

Author Comment

by:jkurant
ID: 40380594
That is facinating, about the scoped script tag.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40380742
It is but the new overrides the old one.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 58

Expert Comment

by:Gary
ID: 40380746
I thought scoped css only works in FF
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40380772
@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
 

Author Comment

by:jkurant
ID: 40383130
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
 
LVL 58

Accepted Solution

by:
Gary earned 250 total points
ID: 40383158
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
 

Author Comment

by:jkurant
ID: 40384280
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
 
LVL 58

Expert Comment

by:Gary
ID: 40384370
The above code does it, styles are applied autmotically, there is no looping.
0
 
LVL 19

Assisted Solution

by:Albert Van Halen
Albert Van Halen earned 150 total points
ID: 40385409
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
 

Author Comment

by:jkurant
ID: 40391017
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
 
LVL 58

Expert Comment

by:Gary
ID: 40391027
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
 
LVL 19

Expert Comment

by:Albert Van Halen
ID: 40391345
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
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 100 total points
ID: 40391364
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

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
In this tutorial viewers will learn how to style a decorative dropcap for the first letter in a paragraph using CSS. In CSS, create a new paragraph class by typing "p.fancy": Then, to style only the first letter of the first sentence, include the ps…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now