5
votes
  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?

4

4 Answers

6
votes

Simple enough:-

newNode.style.backgroundColor = "red";
5
votes

Better to give a classname for the span

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

newNode.className = "spanClass";
3
votes

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>
1
votes

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.