How to Add Span and Style HTML with JavaScript?

Estimated read time 1 min read

You can use JavaScript to add a span element with styles to an HTML element using the createElement() and appendChild() methods. Here’s an example code snippet:

const element = document.getElementById("my-element"); // get the HTML element to add the span to

const span = document.createElement("span"); // create a new span element
span.textContent = "Hello, world!"; // set the text content of the span element

// set the styles of the span element
span.style.color = "red";
span.style.fontSize = "20px";
span.style.fontWeight = "bold";

element.appendChild(span); // add the span element to the HTML element

In the above code, the getElementById() method is used to get an HTML element with the ID “my-element”. A new span element is created using the createElement() method, and the text content of the span is set using the textContent property. The styles of the span element are set using the style property, which is an object that contains properties for each style attribute. Finally, the appendChild() method is used to add the span element to the HTML element.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply