-4
 item1:<input type="text" name="item1"> 

I want to add the text "item1" before the input element in JavaScript.How can I do that?

I have created an input tag in JavaScript using

var i1 =document.createElement("input");

4 Answers4

0

You can use insertAdjacentHTML.

document.querySelector('input').insertAdjacentHTML('beforeBegin', "item1: ");
<input type="text" name="item1"> 

If you are creating the element dynamically, first append it to an element like the body, and then use insertAdjacentHTML.

var i1 = document.createElement("input");
document.body.appendChild(i1)
i1.insertAdjacentHTML('beforebegin', "Item: ");
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Use input.insertAdjacentHTML('beforeBegin', 'HTML'). This code inserts HTML before the start of the input element.

const input = document.querySelector('input')
input.insertAdjacentHTML('beforeBegin', 'item1: ')
<input type="text" name="item1"> 

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

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
0

This code finds all the input in the document with name attributes and prepends the name text in front of the input:

document.querySelectorAll("input[name]").forEach((input) => {
  input.insertAdjacentHTML('beforeBegin', `${input.name}: `);
});
<input type="text" name="item1"><br>
<input type="text" name="item2"><br>
<input type="text" name="item3">
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
0

You can create an element, like this

let input = document.querySelector("input")
let element = document.createElement("YOUR DESIRED ELEMENT GOES HERE")
element.insertBefore(input)
Oliver Hnat
  • 797
  • 4
  • 19
  • index.html:195 Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('YOUR DESIRED ELEMENT GOES HERE') is not a valid name. – Jainish Dabhi Jun 24 '20 at 15:21