I am trying to write a function to mirror the insertAdjacentHTML dom method Element.insertAdjacentHTML and here it is
function insertAdjacent(targetElement) {
'use strict';
return {
insertAfter: function (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild === targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
},
insertAtBegin: function (newElement) {
var fChild = targetElement.firstChild;
if (!fChild) {
targetElement.appendChild(newElement);
} else {
targetElement.insertBefore(newElement, fChild);
}
},
insertAtEnd: function (newElement) {
var lChild = targetElement.lastChild;
if (!lChild) {
targetElement.appendChild(newElement);
} else {
this.insertAfter(newElement, targetElement.lastChild);
}
}
};
}
The function works fine when you insert two different element nodes at the beginning and the end as shown here. But the problem comes when i try to insert the same element node at the beginning and the end as shown here. It only inserts the element node at the end and not at both the beginning and end. What could be causing this issue? Thank you