在insertBefore()中用作父项的内容

时间:2017-03-15 12:03:03

标签: javascript html

这是我试图使用的段落。我试图在使用JavaScript

之前插入一个新段落
<p id="mySpecialParagraph">Well hello there, user</p>

这是关联的javascript,应该在最后一行使用什么代替pId.parentNode.insertBefore?

    var pId = document.getElementById("mySpecialParagraph").nodeValue;

        var pNew = document.createElement("P");
        var text = "This should apperar before the other paragraph";
        var t = document.createTextNode(text);

        pNew.appendChild(t);

        pId.parentNode.insertBefore(pNew, pId);

1 个答案:

答案 0 :(得分:1)

一切都很好。您只需要在nodeValue之后删除getElementById()

var pId = document.getElementById("mySpecialParagraph");

var pNew = document.createElement("P");
var text = "This should apperar before the other paragraph";
var t = document.createTextNode(text);

pNew.appendChild(t);

pId.parentNode.insertBefore(pNew, pId);
<p id="mySpecialParagraph">Well hello there, user</p>