AL-zami
AL-zami

Reputation: 9066

add color dynamically to added text

i am working on this example of appendChild() method.but the difference is here i am trying to add more text to a div dynamically.that was all right.but the hard part is the text i want to add will be red in color.how can i do that? i tried

  text.setAttributes('color',"red");

But it didn't work.so,how this task can be done??please help,thanks!!!!

the full code is given below............

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function create_text(){
    var mydiv = document.getElementById("mydiv");
    var text = document.createTextNode(" New text to add.");

    mydiv.appendChild(text);
}
</script>
</head>
<body>
<button onclick="create_text();">Create Text Node</button>
<div id="mydiv">Welcome, here is some text.</div>
</body>
</html>

Upvotes: 1

Views: 8753

Answers (3)

ComFreek
ComFreek

Reputation: 29414

You would normally have to use CSS properties, however, text nodes cannot have CSS properties applied to them. You therefore need another container element:

You can choose any container element you wish, e.g. div, span, etc. It just needs to be capable of containing a text node. Having an element then allows us to access the styles property and set various styles (the color attribute in your case).

→ jsFiddle

function create_text(){
    var mydiv = document.getElementById("mydiv");

    var container = document.createElement("span");
    var text = document.createTextNode(" New text to add.");

    container.appendChild(text);
    container.style.color = "red";

    mydiv.appendChild(container);
}

Further note:

  • the order of the color assignments and calls of appendChild is arbitrary. The following would also be possible:

    function create_text(){
      var mydiv = document.getElementById("mydiv");
    
      var container = document.createElement("span");
      var text = document.createTextNode(" New text to add.");
    
      container.appendChild(text);
      mydiv.appendChild(container);
    
      container.style.color = "red";
    }
    

Upvotes: 6

pjc
pjc

Reputation: 127

If that's everything in your div, you could try

document.getElementById("mydiv").style.color="#ff0000";

Upvotes: 0

Chris Brickhouse
Chris Brickhouse

Reputation: 648

mydiv.style.color = 'red';

or just in css

#mydiv { color: red; }

if you have other elements inside the div that you don't want to be red, you'd need to wrap the new text in a span or div or another element before appending.

with jquery this would be super easy:

$('#mydiv').append('<span style="color:red">this is new text</span>');

Upvotes: 0

Related Questions