Squill.is.me
Squill.is.me

Reputation: 73

Creating text node and adding CSS

I'm attempting to create a text element and then add CSS attributes

I've tried to use the code below

function create(text){
  var t = document.createTextNode(text);  
  t.style.color = "black"
  t.style.backgroundColor="white"
  t.style.borderRadius="20px"
  t.style.border="4px solid black"
  document.body.appendChild(t);
}
create("hello");

I expect to create a text with a white background and 20px border radius with a 4px solid black border

Upvotes: 0

Views: 1969

Answers (3)

Alex
Alex

Reputation: 467

You are on the right direction. The only thing you need to do is change document.createTextNode(text) with:

var t = document.createElement('span');
t.innerText = text;
\\...
document.body.appendChild(t);

The reason why your code doesn't work is that you can only style HTML tags, and the the text node you created only contains the string you added, without a surrounding tag.

For example:

<span>
  hello
</span>

is a tag with some text with it, while the hello text in the middle is a TextNode.

Hope this makes sense.

Reference:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35096

Instead of a text node, which I don't think you can add styles to, just use a span instead

function create(text){
  var t = document.createElement("span");
  t.innerText = text;  
  t.style.color = "black"
  t.style.backgroundColor="white"
  t.style.borderRadius="20px"
  t.style.border="4px solid black"
  document.body.appendChild(t);
}
create("hello");

Upvotes: 1

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

You are having trouble because text nodes are not meant to be styled.

You should create a DOM element instead. I took your code and update it in order to create a <p> (the nearest element of text node I guess) with your CSS:

function create(text) {
  var t = document.createElement('p');  
  
  t.innerText = text;
  
  t.style.color = "black"
  t.style.backgroundColor="white"
  t.style.borderRadius="20px"
  t.style.border="4px solid black"
  
  document.body.appendChild(t);
}

create("hello");

Upvotes: 1

Related Questions