如何使用节点和.createElement("b")使文本变为粗体?

Pet*_*ere 3 javascript nodes

如果我点击使用节点和createElement的按钮,我必须使文本变粗,但我真的不知道如何...

html(这是我想要加粗的文字):

<p id="textalt">Dies ist ein Text in einem P-Tag</p>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB,  document.getElementById("textneu").nextSibling);
}
Run Code Online (Sandbox Code Playgroud)

我不知道它是如何工作的.

gra*_*ing 6

"我必须使用nodes和createElement来做到这一点"

function fettmachen(){
       // create the "b" element
    var neuB = document.createElement("b");

       // fetch the "textneu" element by ID
    var textneu = document.getElementById("textneu");

       // append the firstChild of "nextneu" to the "neuB"
    neuB.appendChild(textneu.firstChild);

       // append the "neuB" to the "nextneu"
    nextneu.appendChild(neuB);
}
Run Code Online (Sandbox Code Playgroud)


Roc*_*mat 5

我建议,不要添加新标签,只需使用CSS,并在元素中添加一个类.

CSS:

.boldText{
    font-weight: bold;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

function fettmachen(){
    document.getElementById("textalt").className += ' boldText';
}
Run Code Online (Sandbox Code Playgroud)

  • +1样式更好地处理类和CSS而不是插入HTML标记. (2认同)