简体   繁体   中英

How to style an element created with JavaScript

I am trying to style a textbox created with JavaScript by assigning an id to the created element like this:

const x = document.createElement("INPUT");
x.setAttribute("type", "text");
document.getElementById("textBoxForText").appendChild(x);
window.data.appendChild(x);

This is my CSS:

.textBox {
  border: 2px solid red;
  border-radius: 4px;
}

In my HTML file i have tried to call the element by its id, but it doesn't work:

 <div id="textBoxForText" class = "textBox"></div>

How can i solve this issue? I am looking for a solution which avoids using innerHTML if this is possible.

Use the class attribute -

 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; }

Or use the id attribute -

 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; }

Or use the style attribute -

 const camelToHyphen = (s = "") => s.replace ( /([AZ])/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)

Is the script loading before the div with id? How about loading the script after. Use defer or async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM