Javascript 在JS中插入兄弟节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8771921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:26:30  来源:igfitidea点击:

Insert sibling node in JS

javascripthtmldomsiblings

提问by Chris

So I have a div with some pre tags in it, like so:

所以我有一个带有一些 pre 标签的 div,如下所示:

<div id="editor" >
    <pre contentEditable="true">1</pre>
    <pre contentEditable="true">2</pre>
    <pre contentEditable="true">3</pre>
</div>

Now I want to use Javascript to put a new prenode between 1 and 2. I've been trying to do it this way (since I understand the DOM is a doubly linked tree), but I'm getting the sense that maybe the pointers aren't editable as I'm approaching it.

现在我想使用 Javascriptpre在 1 和 2 之间放置一个新节点。我一直在尝试这样做(因为我知道 DOM 是一个双向链接树),但我觉得也许是指针在我接近它时不可编辑。

(just a snippet inside an event handler, ebeing the event)

(只是事件处理程序中的一个片段,e即事件)

var tag = e.srcElement;
    if(tag.nextSibling){
        var next = tag.nextSibling;
        var newPre = document.createElement('pre');
        newPre.setAttribute("contentEditable", "true");
        newPre.innerHTML = "boom";
        tag.nextSibling = newPre;
        newPre.nextSibling = next;
    }

Those last two lines are from my c++ experience, but feel icky in JS. How would I set a new sibling node?

最后两行来自我的 C++ 经验,但在 JS 中感觉很讨厌。我将如何设置一个新的兄弟节点?

回答by Minko Gechev

Here is how I would do that:

这是我将如何做到这一点:

JS

JS

var container = document.getElementById('editor'),
    firstChild = container.childNodes[1];
if (container && firstChild) {
    var newPre = document.createElement('pre');
    newPre.setAttribute("contentEditable", "true");
    newPre.innerHTML = "boom";  
    firstChild.parentNode.insertBefore(newPre, firstChild.nextSibling);    
}

jsfiddle: http://jsfiddle.net/bZGEZ/

jsfiddle:http: //jsfiddle.net/bZGEZ/

回答by Kevin Farrugia

You could also insert a new sibling using insertAdjacentElementor insertAdjacentHTML; both of which take the options beforebegin, beforeend, afterbeginand afterend.

您还可以使用insertAdjacentElementinsertAdjacentHTML插入一个新的兄弟;两者采取的选项beforebeginbeforeendafterbeginafterend

Example:

例子:

var container = document.getElementById('editor'),
firstChild = container.childNodes[1];

var newPre = document.createElement('pre');
newPre.setAttribute("contentEditable", "true");
newPre.innerHTML = "boom";  
firstChild.insertAdjacentElement("afterend", newPre);