最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

colors - JavaScript: how to change CSS style of created span? - Stack Overflow

programmeradmin1浏览0评论
  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 = 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?

Share Improve this question edited Oct 14, 2009 at 10:31 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Sep 25, 2009 at 12:07 mm.mm. 7977 gold badges15 silver badges21 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 8

Simple enough:-

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.

发布评论

评论列表(0)

  1. 暂无评论