Insert sibling node in JS

2019-02-05 17:10发布

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>

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.

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

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

2条回答
可以哭但决不认输i
2楼-- · 2019-02-05 17:26

Here is how I would do that:

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/

查看更多
走好不送
3楼-- · 2019-02-05 17:31

You could also insert a new sibling using insertAdjacentElement or insertAdjacentHTML; both of which take the options beforebegin, beforeend, afterbegin and afterend.

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);
查看更多
登录 后发表回答