javascript - 从 "for"属性创建输入标签,而不更改 HTML

标签 javascript html for-loop dom

在大学类(class)中学习 JavaScript 时遇到问题。这是我的最后一个项目,我在 HTML 代码中遇到的问题是为没有 id 的标签创建一个输入字段,但它有一个“for”元素。它不能使用 JQuery 或 JSON 创建。

所以 HTML 看起来像这样: <"label for="car">您有什么车?<"span class="required"><"/span><"/label">

所以我想我可以创建输入文本字段并将其添加到 DOM:

// Create the input field
var firstCar = document.createElement("input");
// Create the type node and store what the field will be text
var newType = document.createTypeNode("text");
// Create a new ID of car and attach it to the input
var newID = document.createIdNode("car")
/* put the created Element within the HTML with ["this determines which label it will be under"]:*/
var position = document.getElementByTagName("label")[1];
// Insert the element into the position
position.appendChild(firstCar);

我运行了这个,它说 TypeNode 不是我的浏览器中的函数。

最佳答案

这不是设置typeid的方式。试试这个

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

firstCar.type = "text"; // set the type

firstCar.id = "car";    // set the ID

var position = document.getElementsByTagName("label")[1]; // it should be getElements... not getElement...

position.appendChild(firstCar);

关于javascript - 从 "for"属性创建输入标签,而不更改 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711233/

相关文章:

javascript - XMLHttpRequest 无法在 angularjs 中加载

javascript - 如何设置 document.documentElement.innerHTML = 'TEXT' 对齐;

javascript - div parent 和两个 child ,在其他 child 中获取一个 child 的id

javascript - 覆盖库元素类

php - 在 php 中回显 HTML

javascript - 用数字 5 从数组中过滤数字

matlab - 如何在 Octave 中找到函数的导数?

javascript - 有没有用于输入国际电话号码的 jquery 小部件?

javascript - $_POST 没有从 jQuery.post 填充的表单中提取值

c++ - for循环的效率