views:

160

answers:

5

I need a function to change the appearance of some elements in my html page "on the fly", but I am not able to do. The problem is that I cannot use a command like

document.write ('body {background-color: #cccccc;}');

because I need to make the changes effective when the page is already loaded, using a link like

<a onmouseclick="Clicker(1)" href="#">clic</a>

and I cannot use a command like

document.body.style.background='#cccccc';

because I do not know if it can be applied to other not so easy cases, because I need to change the appearance of elements such as td.myclass or sibling elements such as th[scope=col]+th[scope=col]+th[scope=col].

How can I do it? Thanks!

+1  A: 

You can use the id attribute for as many elements as you like, but they must be unique. You can also use the class attribute, but to find the specific element you want will be bit tougher.

Then, using JavaScript, you can use the document.getElementById function to retrieve the DOMElement object to set CSS properties on. For classes, you will need to first get all the elements with the specified tag name by calling document.getElementsByTagName, then iterating over the resulting array and checking if each element has the provided class name, and if it does, then adding to an array, which after the loop gets returned.

Jacob Relkin
+1  A: 

If you want to use complex selector like th[scope=col], use jQuery

N 1.1
+1  A: 

The stylesheets can be manipulated directly in JS with the document.styleSheets list.

KennyTM
+3  A: 

If you need to change styles of elements you need to match with CSS selectors I suggest using frameworks such as jQuery for that:

$('td.myclass').css('background-color', '#ff0000');

More about setting CSS properties: http://api.jquery.com/css/

More about selecting elements: http://api.jquery.com/category/selectors/

If you need to update existing (already loaded) page, wrap your stuff in this:

jQuery(function($) {
    // do your stuff here
});
Marko Dumic
+1  A: 
document.getElementsByClassName('myclass')[NUMBER].style.['background-color'] = '#ccc';

Example:

document.getElementsByClassName('myclass')[0].style.['background-color'] = '#ccc';
document.getElementsByClassName('myclass')[1].style.['background-color'] = '#ccc';


If you want change all td.myclass

var myObj = document.getElementsByClassName('myclass');
for(var i=0; i<myObj.length; i++){
  myObj[i].style.['background-color'] = '#ccc';
}
gmunkhbaatarmn