# Reusable function for insertAfter

**URL:** <https://forum.kirupa.com/t/reusable-function-for-insertafter/636992>\
**Category:** Uncategorized\
**Created:** [August 4, 2017, 6:03pm UTC](https://forum.kirupa.com/t/reusable-function-for-insertafter/636992 "2017-08-04T18:03:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![iamgeorgegreene](https://avatars.discourse-cdn.com/v4/letter/i/aeb1de/32.png) [@iamgeorgegreene](https://forum.kirupa.com/u/iamgeorgegreene)\
**Post date:** [August 4, 2017, 6:03pm UTC](https://forum.kirupa.com/t/reusable-function-for-insertafter/636992/1 "2017-08-04T18:03:14Z")

</div>

Question about this function as seen in the book Javascript for Absolute Beginners:

This is the function:

```auto
funtion insertAfter (target, newElement) {
   target.parentNode.insertBefore(newElement, target.nextSibling) ;
}

```

My question: why is the second argument target.nextSibling and what does this mean? I thought it should be just target alone.

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [August 4, 2017, 9:17pm UTC](https://forum.kirupa.com/t/reusable-function-for-insertafter/636992/2 "2017-08-04T21:17:28Z")

</div>

nextSibling is the next element in the current set of element children. So, for example,

```xml
<div>
  <b></b><i></i><code></code>
</div>

```

Here we have a div and a bunch of elements inside (the children). The div is the parent, b is the firstChild, and i is b’s nextSibling. i’s nextSibling would be code. The last child, code, has no nextSibling since its at the end of the set of children.

What insertAfter does is inserts an element after another element. It does this by calling a different method, insertBefore. insertBefore inserts before another element. To make a before behave like an after, you call before on the _next_ element in the set.

Lets say we’re inserting an img between b and i.

```xml
<div>
  <b></b><img><i></i><code></code>
</div>

```

The “before” approach would be inserting it before i. The “after” approach would be inserting after b. So how insertAfter is written is using the “before” approach. However after is given a “target” of b, so in going with the before approach, we need to get to i from the b, and since its next to b (before the insertion occurs), its retrieved with target.nextSibling.

---

<div class="post-metadata">

**Author:** ![iamgeorgegreene](https://avatars.discourse-cdn.com/v4/letter/i/aeb1de/32.png) [@iamgeorgegreene](https://forum.kirupa.com/u/iamgeorgegreene)\
**Post date:** [August 8, 2017, 8:16am UTC](https://forum.kirupa.com/t/reusable-function-for-insertafter/636992/3 "2017-08-08T08:16:52Z")

</div>

Thank you!
