最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to changeadd p tag style using DOM? - Stack Overflow

programmeradmin6浏览0评论

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.

Share Improve this question edited Feb 21, 2014 at 13:21 Zword 6,7853 gold badges29 silver badges53 bronze badges asked Feb 21, 2014 at 6:49 pandoragamipandoragami 5,57515 gold badges72 silver badges121 bronze badges 5
  • 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
Add a ment  | 

4 Answers 4

Reset to default 5

Try 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 :)

发布评论

评论列表(0)

  1. 暂无评论