dksb
dksb

Reputation: 21

javascript to access a specific css selector property

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
      }
}

Upvotes: 2

Views: 207

Answers (2)

mastazi
mastazi

Reputation: 1672

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.

Upvotes: 1

Christophe
Christophe

Reputation: 28124

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";

Upvotes: 1

Related Questions