简体   繁体   中英

JavaScript: how to change CSS style of created span?

  newNode = document.createElement("span");
  newNode.innerHTML = "text";
  range.insertNode(newNode);

Is it possible to make the text in innerHTML with red background color? I want to add style="background-color:red" to just created span. Is it possible? Or it must have some id, and then I can change this span with jQuery ?

很简单: -

newNode.style.backgroundColor = "red";

Better to give a classname for the span

<style>
    .spanClass { background-color: red; }
</style>

newNode.className = "spanClass";

This worked for me:

var spanTag1 = document.createElement('span');
spanTag1.innerHTML = '<span style="color:red">text</span>';

OR

add class using js and set css to that class

var spanTag1 = document.createElement('span');
spanTag1.className = "mystyle";

Now set style to that class

<style> 
    .mystyle {
        color:red;
    }
</style>

You can add attributes directly to the DOM object. The style attribute can be assigned by this way too. Example:

var span = document.createElement("span");
span.setAttribute("style","color:white;background-color:red;");

var text = document.createTextNode("My text");
span.appendChild(text);

Of course you have to add this element created to their parent object in your page:

var parent = document.getElementById("parentObject");
parent.appendChild(span);

This method "setAttribute()" lets you to add other non-standard attributes used by animations and custom jquery options to your HTML standard tags.

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