在JS中插入兄弟节点 [英] Insert sibling node in JS

查看:3202
本文介绍了在JS中插入兄弟节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

现在我想使用Javascript放一个新的 pre 节点在1和2之间。我一直在尝试这样做(因为我明白DOM是一个双重链接的树),但我感觉到,也许指针是不可编辑的,因为我'接近它。

Now I want to use Javascript to put a new pre node 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.

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

(just a snippet inside an event handler, e being the event)

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;
    }

最后两行来自我的c ++体验,但在JS中感觉到icky。我如何设置一个新的兄弟节点?

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

推荐答案

这是我将如何做:

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/

这篇关于在JS中插入兄弟节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆