I want a variable font-size
in my P
tag using the DOM but I can't seem to find a way to access it to change the styles. I tried this,
document.body.p.style.font-size = ""+p_var+"px";
along with trying several ways using setAttribute
with no luck. Can anyone please show me how to change it if it is possible.
I want a variable font-size
in my P
tag using the DOM but I can't seem to find a way to access it to change the styles. I tried this,
document.body.p.style.font-size = ""+p_var+"px";
along with trying several ways using setAttribute
with no luck. Can anyone please show me how to change it if it is possible.
-
you want to set this through javascript? why dont you use
css
? – Amir Sherafatian Commented Feb 21, 2014 at 6:53 - Because CSS doesn't have variables I can change at runtime no? – pandoragami Commented Feb 21, 2014 at 6:54
- 1 'p' is Not an object. but an array of objects. you need to iterate over the elements of this array. – Axel Amthor Commented Feb 21, 2014 at 6:54
- Font size is applied through an element's style properties. These can be modified as properties of the element's style object, or through CSS, which can be modified by CSS rules set through a selector or class. – RobG Commented Feb 21, 2014 at 6:54
- @am1r_5h—I don't see a jQuery tag on the OP. A collection of P elements can be created without using jQuery. – RobG Commented Feb 21, 2014 at 6:56
4 Answers
Reset to default 5Try following code:
var s=document.getElementsByTagName('p');
for(i=0;i<s.length;i++)
{
s[i].setAttribute("style","font-size:"+p_var+"px");
}
Demo Fiddle
Try something like this,
<p id="myP">This is a paragraph.</p>
JS
document.getElementById("myP").style.fontSize = ""+p_var+"px";
else if you want to set style for all the <p>
tags try the below
var node;
node = document.getElementsByTagName('p');
for (var i = node.length-1; i>=0; i--) {
node[i].style.fontSize = ""+p_var+"px";
}
Also if you need to have same class name for <p>
tags as below,
<p class="myP">This is a paragraph.</p>
<p class="myP">This is a paragraph.</p>
try this,
var node;
node = document.getElementsByClassName('myP');
for (var i = node.length-1; i>=0; i--) {
node[i].style.fontSize = ""+p_var+"px";
}
Using jquery it can be done as
$("p").css({"font-size":"30px"});
First, prepair a css class for example
.font30 {
font-size: 30px;
}
Then do with jquery
$("p").addClass("font30");
It's good practice to work with class instead of inline css :)