0

I am attempting to do a jquery .after in pure JS.

I have the following script that works for the first div where I append by getElementById but not the second where I am using getElementsByClassName

JSFiddle

How can I successfully append by using the element's class?

HTML

<div id="first-div">First Div - found by ID</div>
<br>
<div class="second-div">Second Div - found by ClassName</div>

JS

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

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

var element2 = document.createElement("div");
element2.className = 'row'
element2.innerHTML = 'Text to append to second div by class';
var div2 = document.getElementsByClassName('second-div');
insertAfter(div2, element2);
redditor
  • 4,196
  • 1
  • 19
  • 40
  • Possible duplicate of [getElementsByClassName issue](https://stackoverflow.com/questions/12377734/getelementsbyclassname-issue) – DocMax Oct 15 '17 at 16:26
  • In addition to using the first item in the returned array from `getElementsByClassName`, you could alternately use `querySelector`. – DocMax Oct 15 '17 at 16:27

2 Answers2

1
var div2 = document.getElementsByClassName('second-div')[0];

getElementsByClassName returns a iterable so you have to say which one [0] for first

Walle Cyril
  • 3,087
  • 4
  • 23
  • 55
0

getElementsByClassName returns all the elements of that class, therefore the correct way is to iterate through each item

var element2 = document.createElement("div");
element2.className = 'row'
element2.innerHTML = 'Text to append to second div by class';
var div2 = document.getElementsByClassName("second-div");
for(var i = 0; i < div2.length; i++)
{
   insertAfter(div2.item(i), element2);
}
var div2 = document.getElementsByClassName('second-div');
redditor
  • 4,196
  • 1
  • 19
  • 40