通过向其添加 class 将 setAttribute 用于 ID

using setAttribute to ID by adding class to it

我是 JavaScript 的新手。我正在通过将 class 添加到 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/

如有任何建议,我将不胜感激。

您的代码运行良好,您需要为 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>