javascriptecmascript-6insertadjacenthtml

Inserting element into DOM at a specific place is not working


I would like to insert an input type=text field between p and input type=submit using insertAdjacentHTML, but it’s not working. A string [object HTMLInputElement] gets inserted instead of an input element.

What am I missing? Please share if there is a more elegant way to do this.

Here is my code:

const form = document.forms[0]
const submitButton = form.querySelector("[type='submit']")

const foobar = Object.assign(document.createElement("input"), {
  type: "text",
  name: "Foobar",
  readOnly: "true"
})
  
submitButton.insertAdjacentHTML("beforebegin", foobar)
<form>
  <fieldset>
    …
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    <input type=submit value=Submit>
  </fieldset>
</form>


Solution

  • insertAdjacentHtml is used for inserting HTML text, a string. To insert DOM nodes, use insertBefore:

    submitButton.parentNode.insertBefore(foobar, submitButton)