0

I want to append a span element after an input field but appending the span to the input field using appendChild()is not working as I'd like. How can I append an inline element after another element in js?

Here's my code to create the span element

    var span = document.createElement("span");
    span.setAttribute("id", inputNameValues[i] + "-error");
    var errorText = document.createTextNode("* " + inputLabels[i] + " must not be left blank");
    span.appendChild(errorText);
    input.appendChild(span);
PumpkinBreath
  • 831
  • 1
  • 9
  • 22
  • Answered here: https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib – Bibberty Mar 07 '19 at 22:58

1 Answers1

0

Looks like you're appending span as a child of input, rather than as a sibling.

I think you might be better using Element.insertAdjacentHTML() instead.

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

  • I am getting this error: Uncaught DOMException: Failed to execute 'insertAdjacentHTML' on 'Element': The element has no parent. My input tags are inside a form which is inside a fieldset, how can it not have a parent node? – PumpkinBreath Mar 07 '19 at 23:11
  • I've copied it into codepen and having a look – Chris Halley Mar 07 '19 at 23:18
  • Are you definitely defining input as a variable somewhere? I'm getting that as an error in codepen. – Chris Halley Mar 07 '19 at 23:20
  • I have realised the problem, I am creating all the HTML dynamically and was trying to reference parentNode before I'd actually appended its parent to the DOM. Ooops... thanks for the assistance – PumpkinBreath Mar 07 '19 at 23:30