简体   繁体   中英

Insert after firstchild div in pure JS

I am using pure JS to append a HTML string after a div that has been found by getElementById . This is working correctly but I would now like to append after the first child of the found element.

JSFiddle

HTML

First Div Div I want to append to Other div...

(the second and third divs have no id or class)

JS

 function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } var element1 = document.createElement("div"); element1.innerHTML = 'Text to append'; var div1 = document.getElementById('first-div'); insertAfter(div1, element1); 

Current result is:

First Div Div I want to append to Other div... Text to append

I am trying to achieve this:

First Div Div I want to append to Text to append Other div...

I have tried

 var div1 = document.getElementById('first-div').firstchild; 

but this is not working

As I said in my comment, your example suggests the div you want to append to is not the child, but rather the sibling of "first-div". It should look like

<div id="first-child">
    <div>Div I want to append to</div>
</div>

Then the first child of the parent div can be found with

var div2 = div1.children[0];

I fiddled with your fiddle:

http://jsfiddle.net/01qrmj36/

If you remove the referenceNode from the insertBefore call in your insertAfter example it should behave how you want it to, eg:

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode);
}

var element1 = document.createElement("div");
element1.innerHTML = 'Text to append';
var div1 = document.getElementById('first-div');
insertAfter(div1, element1);

Omitting the referenceNode from insertBefore defaults to inserting the new node at the end of the list of child nodes, see more here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM