通过向其添加类来使用setAttribute到ID

时间:2017-10-08 05:39:16

标签: javascript setattribute

我是JavaScript新手。我正在通过向id添加一个类来练习setAttribute:

当我点击按钮时,我想将字体的颜色更改为红色。但是,它并没有改变。

我从w3school借了一个类似的例子,但是添加了一个id。

HTML:

<h1 id = "Hello">Hello World</h1>

<p>Click the button to add a class attribute with the value of "democlass" to the h1 element.</p>

<button onclick="myFunction()">Try it</button>

JavaScript的:

// returns a html element (id)
var $ = function(id) {
return document.getElementById(id);
};

function myFunction() {
$("Hello").setAttribute("class", "democlass"); 
}

CSS:

#Hello.democlass {
color: red;
}

https://jsfiddle.net/1vzmqgqv/

我很感激任何建议。

1 个答案:

答案 0 :(得分:1)

您的代码运行良好,您需要更改JavaScript的 jsfiddle 设置。

转到JavaScript部分,然后点击设置图标,将LOAD TYPE更改为No wrap - in <body>

https://jsfiddle.net/ddg6gdbw/

// returns a html element (id)
var $ = function(id) {
  return document.getElementById(id);
};

function myFunction() {
  $("Hello").setAttribute("class", "democlass"); 
}
#Hello.democlass {
  color: red;
}
<h1 id = "Hello">Hello World</h1>

<p>Click the button to add a class attribute with the value of "democlass" to the h1 element.</p>

<button onclick="myFunction()">Try it</button>