Pregunta

How do you change the font-size of a custom css style using javascript?

I've seen examples of how to replace inline styles using javascript but I can't find how to replace an attribute like font-size in a non-inline custom style in a header. For example I'd like to use javascript to change the font-size from 12px 20px using javascript.

<head>
<style>
.mystyle{
font-size:12px;
}
</style>

¿Fue útil?

Solución

Here is the code:

html:

<p class="mystyle">This is some text.</p>

javascript:

window.onload=function(){
document.getElementsByClassName("mystyle")[0].style.fontSize="120%";
}

You can also set the fontsize as smaller , larger, in length units and also inherit font-size of parent element.

Otros consejos

document.getElementsByClassName('CLASSNAME')

gives you an array with all the class elements, you could use a loop to change every nodes style, you can access them like a usual array with []. I'm not sure if there's a more comfortable way

This will allow you to set the font-size of an object.

Object.style.fontSize="value|inherit"

So, for example, if you open console on this page and run:

document.getElementsByTagName('h1')[0].style.fontSize = '35px'

You will see the header of this page increase.

In order to change the style sheet specified in a style element, you can modify the element content:

s = document.getElementsByTagName('style')[0];
s.innerHTML += '.mystyle { font-size: 20px; }';

This does not change the existing rule but appends one that overrides it.

Alternatively, you can use the sheet property of the style element as defined in CSSOM:

var sh = document.getElementsByTagName('style')[0].sheet;
sh.insertRule('.mystyle { font-size: 20px; }', sh.cssRules.length);

If you really wanted to replace a rule in the style element and not just override it, you would need to locate it, traversing the cssRules object and getting an index, then calling deleteRule and then insertRule.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top