[英]How to add text before input element using JavaScript?
item1:<input type="text" name="item1">
I want to add the text "item1" before the input element in JavaScript.How can I do that?我想在 JavaScript 的输入元素之前添加文本“item1”。我该怎么做?
I have created an input tag in JavaScript using我使用在 JavaScript 中创建了一个输入标签
var i1 =document.createElement("input");
You can use insertAdjacentHTML
.您可以使用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
.如果您要动态创建元素,首先将 append 设置为像 body 这样的元素,然后使用insertAdjacentHTML
。
var i1 = document.createElement("input"); document.body.appendChild(i1) i1.insertAdjacentHTML('beforebegin', "Item: ");
Use input.insertAdjacentHTML('beforeBegin', 'HTML')
.使用input.insertAdjacentHTML('beforeBegin', 'HTML')
。 This code inserts HTML before the start of the input element.此代码在输入元素的开头插入 HTML。
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 MDN 参考: 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
:此代码查找文档中具有name
属性的所有input
,并在input
前添加name
文本:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.