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");
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");
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: ");
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
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">
You can create an element, like this
let input = document.querySelector("input")
let element = document.createElement("YOUR DESIRED ELEMENT GOES HERE")
element.insertBefore(input)