2

I have this in a css file

.datagrid table tbody td { color: #00496B; border-left: 1px solid
    #E1EEF4; font-size: 16px ;font-weight: normal; }

how can I use javascript to change the font-size dynamically? this following codes worked on all td but how can I access the specific td under .datagrid? any help is appreciated.

css('td', 'font-size', '9px');
function css(selector, property, value) {
      for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
          //Try add rule
          try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
          } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
      }
}
2
  • You didn't try it with the selector .datagrid table tbody td instead? Commented Nov 24, 2012 at 2:04
  • 1
    The easiest way to change the font size for all the tables dynamically would be having the data grids inherit the font size from a container, and changing the class of the container to one that specifies a larger font. Analogously, for changing a single cell, just add a class (say highlight) that would give it a larger font td.highlight { font-size: 20px; } Commented Nov 24, 2012 at 2:54

2 Answers 2

1

The easiest way to map css rules is to use querySelectorAll:

document.querySelectorAll(".datagrid table tbody td")

This is supported in all recent browsers.

If you are targeting a single element:

document.querySelector(".datagrid table tbody td")

And to modify the font size on this specific element:

document.querySelector(".datagrid table tbody td").style.fontSize="12px";
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of traversing the CSS, you might use document.getElementById to select the element if it has a unique ID, otherwise you can use getElementByTagName as follows:

document.getElementsByTagName('div')[0] //the first div in the document
document.getElementsByTagName('div')[1] //the second div... etc...

then you can change the inline css e.g. <div id="mydiv" style="width: 200px;">

document.getElementById('mydiv').style.width = "200px"

If, otherwise, you don't want to insert inline styles, you can access the external CSS with document.styleSheets[index], where index is used if you have more than one stylesheeet, otherwise just use document.styleSheets[0], then the rules are in another array, which is cssRules[index] so e.g. with document.styleSheets[0].cssRules[0] you select the first rule of the first external CSS.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.