我正在尝试通过为创建的元素分配一个id来设置用JavaScript创建的文本框的样式,如下所示:
const x = document.createElement("INPUT");
x.setAttribute("type", "text");
document.getElementById("textBoxForText").appendChild(x);
window.data.appendChild(x);
这是我的CSS:
.textBox {
border: 2px solid red;
border-radius: 4px;
}
在我的HTML文件中,我试图通过其ID调用该元素,但是它不起作用:
<div id="textBoxForText" class = "textBox"></div>
我该如何解决这个问题?我正在寻找一种解决方案,如果可能的话,避免使用innerHTML。
答案 0 :(得分:2)
使用class
属性-
const p =
document.createElement("p")
const t =
document.createTextNode("this is a styled paragraph")
p.setAttribute("class", "textbox") // <--
p.appendChild(t)
document.body.appendChild(p)
.textbox { /* class selector, .textbox */
padding: 1rem;
color: tomato;
border: 1px solid;
border-radius: 5px;
}
或使用id
属性-
const p =
document.createElement("p")
const t =
document.createTextNode("this is a styled paragraph")
p.setAttribute("id", "textbox") // <--
p.appendChild(t)
document.body.appendChild(p)
#textbox { /* id selector, #textbox */
padding: 1rem;
color: tomato;
border: 1px solid;
border-radius: 5px;
}
或使用style
属性-
const camelToHyphen = (s = "") =>
s.replace
( /([A-Z])/g
, (_, m) => `-${m.toLowerCase()}`
)
const toCss = (o = {}) =>
Object
.entries(o)
.map(([ k, v ]) =>
`${camelToHyphen(k)}:${v};`
)
.join("")
const textbox = { /* javascript object, textbox */
padding: "1rem",
color: "tomato",
border: "1px solid",
borderRadius: "5px",
}
const p =
document.createElement("p")
const t =
document.createTextNode("this is a styled paragraph")
p.setAttribute("style", toCss(textbox)) // <--
p.appendChild(t)
document.body.appendChild(p)
答案 1 :(得分:1)
脚本是否在具有ID的div之前加载? 之后如何加载脚本。使用延迟或异步