JavaScript中的getElementsByTagName方法---不起作用

时间:2019-02-22 08:49:24

标签: javascript html css

function changeStyling() {
  var para = document.getElementsByTagName("p");
  para[0].style.fontSize = 25;
  para[1].style.fontSize = "red";
}
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>

<button onclick="changeStyling()">click</button>

6 个答案:

答案 0 :(得分:7)

应为fontSize="25px";color="red"

function changeStyling() { 

  var para = document.getElementsByTagName("p");
  para[0].style.fontSize="25px"; 
  para[1].style.color="red"; 
}
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<button onclick="changeStyling()">
    click
</button>

答案 1 :(得分:1)

getElementsByTagName没什么问题,这是错误的地方:

  • 对于字体大小,您需要指定一个单位,例如 px
  • 要设置颜色,显然不能将 fontSize 设置为 color 。...

改进的代码:

function changeStyling() {
  var para = document.getElementsByTagName("p");
  para[0].style.fontSize = "25px";
  para[1].style.color = "red";
}
<p>This is paragraph 0</p>
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>

<button onclick="changeStyling()">click</button>

答案 2 :(得分:1)

使用px设置字体大小

function changeStyling() {
  var para = document.getElementsByTagName("p");
  para[0].style.color = 'red';
  para[1].style.fontSize = '24px';

}
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>

<button onclick="changeStyling()">
    click
</button>

答案 3 :(得分:0)

getElementsByTagName正常工作。但是fontSize需要一个string。也 要添加颜色,您需要为css属性设置颜色

function changeStyling() {
  var para = document.getElementsByTagName("p");
  para[0].style.fontSize = '25px';
  para[1].style.color = "red";


}
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>
<p>This is the paragrap 1</p>

<button onclick="changeStyling()">
	    click
	</button>

答案 4 :(得分:0)

function changeStyling() {


  var para = document.getElementsByTagName("p");
  // console.log(para);
  para[0].style.fontSize = '25px';
  para[1].style.color = "red";


}
<p> asdASDas </p>
<p> asdASDas </p>
<p> asdASDas </p>
<p> asdASDas </p>

<button onclick="changeStyling()"> push me </button>

尝试一下,我在fontSize内推入一个以像素为单位的字符串,并用红色为字符串着色。

答案 5 :(得分:0)

您输入了错误的样式

para[0].style.fontSize = "25px"; // string with px
para[1].style.color = "red"; // color, instead of fontSize