0

I have this working code but instead of it inserting before I would like to insert after. I'm just not sure how to go about this. Thanks in advance

document.addEventListener("keydown", keyDownBody, false);

function keyDownBody(e) {
var keyCode = e.keyCode;
if(keyCode==65) {
  myFunction();
}
}
function myFunction()
{var a = document.createElement("IMG");

a.src="img/one/a1.gif?rand_number=" + Math.random();

document.body.insertBefore(a,document.body.firstElementChild);}

document.addEventListener("keydown", keyDownBody2, false);

function keyDownBody2(e) {
var keyCode = e.keyCode;
if(keyCode==66) {
  myFunctionb();
}
}
function myFunctionb()
{var b = document.createElement("IMG");

b.src="img/one/b1.gif?rand_number=" + Math.random();

document.body.insertBefore(b,document.body.firstElementChild);}
  • There is no `insertAfter`. You have to find the next element and insert before it. – Barmar Jun 01 '17 at 23:22
  • Possible duplicate of [How to do insert After() in JavaScript without using a library?](https://stackoverflow.com/questions/4793604/how-to-do-insert-after-in-javascript-without-using-a-library) – Syfer Jun 02 '17 at 01:55

2 Answers2

0

You can use the appendChild function. I have changed your code to do it in one place.

https://jsfiddle.net/w05Lem0s/

Simply do:

document.body.appendChild(a,document.body.firstElementChild);
0

You can find next element and insert before it

function myFunctionb() {
  var b = document.createElement("IMG");

  b.src = "img/one/b1.gif?rand_number=" + Math.random();

  document.body.insertBefore(b, document.body.firstElementChild.nextSibling);
}
Toan Tran
  • 1,937
  • 1
  • 24
  • 37