Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
mm. Avatar asked Sep 25 '09 12:09

mm.


3 Answers

Simple enough:-

newNode.style.backgroundColor = "red";
like image 113
AnthonyWJones Avatar answered Sep 27 '22 00:09

AnthonyWJones


Better to give a classname for the span

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

newNode.className = "spanClass";
like image 25
rahul Avatar answered Sep 25 '22 00:09

rahul


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>
like image 39
Renascent Avatar answered Sep 23 '22 00:09

Renascent