CUTCODEDOWN
Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, or have issues with using the registration form, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: All the different ways to add a node to the DOM  (Read 1409 times)

Jason Knight

  • Administrator
  • Hero Member
  • *****
  • Posts: 1049
  • Karma: +188/-1
    • CutCodeDown -- Minimalist Semantic Markup
All the different ways to add a node to the DOM
« on: 4 Nov 2019, 05:36:38 am »
Whilst most JS coders are vaguely familiar with Element.appendChild and may have heard of Element.insertBefore, the possibilities using the various next/previous/child methods and how insertBefore targets a child element and not the Element of the method often eludes understanding...

... when really there are four possibilities that really opens doors to what you can do on the DOM.

Let's say we have this:

Code: [Select]
<div>
  <div id="section">Section 1</div>
</div>

and:

Code: [Select]
var
section = document.getElementById('section'),
testTextNode = document.createTextNode(' HEY! ');

Let's say you want to insert testTextNode into section at the end of its text. That's easy.

Code: [Select]
section.appendChild(testTextNode);

That would give you the rought equivalent of:

Code: [Select]
<div>
  <div id="section">Section 1 HEY! </div>
</div>

But what if you want it before? Well, that's where insertBefore comes into play... but the second paramenter of insertBefore is the trick, as you have to say WHAT to put it before. How about the firstChild?

Code: [Select]
section.insertBefore(testTextNode, section.firstChild);

Sure enough, you get roughly this:

Code: [Select]
<div>
  <div id="section"> HEY! Section 1</div>
</div>

Neat, huh? Well let's dial it up a notch. How about inserting it BEFORE #section?

Code: [Select]
section.parentNode.insertBefore(testNtextNode, section);

... and we get:

Code: [Select]
<div>
   HEY! <div id="section">Section 1</div>
</div>

as our result. We can also put it after.

Code: [Select]
section.parentNode.insertBefore(testTextNode, section.nextSibling);

Which gives us:

Code: [Select]
<div>
  <div id="section">Section 1</div> HEY!
</div>

So to sum up:

Code: [Select]
// appendChild for last in targeted element
section.appendChild(testTextNode);

// insertBefore firstChild for first in target
section.insertBefore(testTextNode, section.firstChild);

// target.parentNode to target places before
section.parentNode.insertBefore(testTextNode, section);

// target.parentNode to target.nextSibling for after
section.parentNode.insertBefore(testTextNode, section.nextSibling);

Powerful simple techniques that I rarely see, and again where the power of the DOM really shines, as you can insert any DOM Node in this manner.
« Last Edit: 4 Nov 2019, 11:04:09 am by Jason Knight »
We are all, we are all, we are all FRIENDS! For today we're all brothers, tonight we're all friends. Our moment of peace in a war that never ends.

coothead

  • Sr. Member
  • ****
  • Posts: 390
  • Karma: +89/-0
  • I smile benignly
    • coothead's stuff ~ an eclectic collection
Re: All the different ways to add a node to the DOM
« Reply #1 on: 4 Nov 2019, 06:41:39 am »
Hi there Jason,

you have some typos in your summary...

Code: [Select]
// target.parentNode to target places before
section.insertBefore(testTextNode, section.firstChild);

// target.parentNode to target.nextSibling for after
section.parentNode.insertBefore(testNtextNode, section.nextSibling);

It should read....

Code: [Select]
// target.parentNode to target places before
   section.parentNode.insertBefore(testTextNode, section);

// target.parentNode to target.nextSibling for after
   section.parentNode.insertBefore(testTextNode, section.nextSibling);

While I am here, may I suggest that you also provide examples,
if possible, that reverse these four procedures.  :)

coothead
~ the original bald headed old fart ~

Jason Knight

  • Administrator
  • Hero Member
  • *****
  • Posts: 1049
  • Karma: +188/-1
    • CutCodeDown -- Minimalist Semantic Markup
Re: All the different ways to add a node to the DOM
« Reply #2 on: 4 Nov 2019, 06:55:25 am »
you have some typos in your summary...

Good catch, fixed. I shouldn't have written the summary whilst having breakfast.


While I am here, may I suggest that you also provide examples,
if possible, that reverse these four procedures.  :)

Well undoing it if you have the element to remove, let's call it "target".

Code: [Select]
target.parentNode.removeChild(target);

Which brings us to the lovely little gem that is node flushing.

Code: [Select]
function flush(e) {
  while (e.firstChild) e.removeChild(e.firstChild);
}

Which acts much akin to

Code: [Select]
e.innerHTML = '';
...but without inducing any unwanted side effects and in MOST cases executing faster if the parser time is included. Sadly, JavaScript cannot benchmark the parser side of things by itself, so you have to nail it hard and watch system load from tools like TOP, "task manager", etc.

I'll try to come up with some examples when I have a moment.

« Last Edit: 4 Nov 2019, 06:58:48 am by Jason Knight »
We are all, we are all, we are all FRIENDS! For today we're all brothers, tonight we're all friends. Our moment of peace in a war that never ends.

coothead

  • Sr. Member
  • ****
  • Posts: 390
  • Karma: +89/-0
  • I smile benignly
    • coothead's stuff ~ an eclectic collection
Re: All the different ways to add a node to the DOM
« Reply #3 on: 4 Nov 2019, 07:10:56 am »
Hi there Jason,

you still have a typo, even after your editing....

Code: [Select]

// target.parentNode to target.nextSibling for after
section.parentNode.insertBefore(testNtextNode, section.nextSibling);

If you are unable to spot it I will narrow it down a little...

stNte

...should be..

stTe.  :D

coothead

~ the original bald headed old fart ~

jmrker

  • Junior Member
  • *
  • Posts: 43
  • Karma: +1/-0
Re: All the different ways to add a node to the DOM
« Reply #4 on: 5 Nov 2019, 12:56:01 am »
I enjoyed this discussion.  Here is a action synopsis of each item:
Code: [Select]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<title> DOM Manipulator </title>
<!-- From: https://forums.cutcodedown.com/index.php?topic=57.0;topicseen -->

<style>
 div { border: 1px solid red; width: 10em; }
 .LASTsection { border: 0; }
</style>
</head>
<body>

<div>
  <div id="section">Section 1</div>
</div> <br>

<div>
  <div id="section1">Section 2</div>
</div> <br>

<div>
  <div id="section2">Section 3</div>
</div> <br>

<div>
  <div id="section3">Section 4</div>
</div> <br>

<div>
  <div id="section4">Section 5</div>
</div> <br>

<button id="btnRemove">Remove LAST Section</button>
<div class="LASTsection">
  <div class="LASTsection" id="section5">LAST Section To Be Removed</div>
</div> <br>

<script>
console.clear();

var section = document.getElementById('section1'),
    testTextNode = document.createTextNode(' append HEY! ');
    section.appendChild(testTextNode);

    section = document.getElementById('section2'),
    testTextNode = document.createTextNode(' insert HEY! ');
    section.insertBefore(testTextNode, section.firstChild);

    section = document.getElementById('section3'),
    testTextNode = document.createTextNode(' inject HEY! ');
    section.parentNode.insertBefore(testTextNode, section);

    section = document.getElementById('section4'),
    testTextNode = document.createTextNode(' trail HEY! ');
    section.parentNode.insertBefore(testTextNode, section.nextSibling);

  function flush(e) {  // acts like e.innerHTML = '';
    while (e.firstChild) e.removeChild(e.firstChild);
  }

// for testing removal of element
    function removeLASTsection() { flush(document.getElementById('section5')); }
    document.getElementById('btnRemove').addEventListener( 'click', removeLASTsection );

</script>

</body>
</html>


Changed IDs to protect the innocent.
Modified descriptions: insert, append, inject, trail to highlight differences.
« Last Edit: 5 Nov 2019, 12:58:19 am by jmrker »

Jason Knight

  • Administrator
  • Hero Member
  • *****
  • Posts: 1049
  • Karma: +188/-1
    • CutCodeDown -- Minimalist Semantic Markup
Re: All the different ways to add a node to the DOM
« Reply #5 on: 5 Nov 2019, 10:01:27 am »
Modified descriptions: insert, append, inject, trail to highlight differences.
I've always used the terms first, last, before, and after, though I'm thinking first, last, previous and next might be more appropriate.

Why? To match up with firstChild, lastChild, previousSibling, and nextSibling which is basically what the inserted element becomes.

But whatever floats your boat.
We are all, we are all, we are all FRIENDS! For today we're all brothers, tonight we're all friends. Our moment of peace in a war that never ends.

jmrker

  • Junior Member
  • *
  • Posts: 43
  • Karma: +1/-0
Re: All the different ways to add a node to the DOM
« Reply #6 on: 5 Nov 2019, 12:50:15 pm »
Yes, probably better words could have been used.
They were just used in the "heat of the moment"
as I was trying to highlight the different actions of the code.

 

SMF spam blocked by CleanTalk

Advertisement