Reputation: 51
I was coding this morning a simple contact manager, and I found that I can't change the style of the text in JavaScript ! the Problem :
function addcontact() {
var ul = document.getElementById("list");
var firstname = document.getElementById("input_firstname");
var lastname = document.getElementById("input_lastname");
var li = document.createElement("li");
li.setAttribute('id',firstname.value);
li.appendChild(document.createTextNode("Firstname:" + firstname.value + ", Lastname: " + lastname.value ));
ul.appendChild(li);
}
li.appendChild(document.createTextNode("Firstname:" + firstname.value + ", Lastname: " + lastname.value ));
In this line I can't change the style of "Firstname: " . I tried to add some tags but nothing happened!
How can i solve this problem?
Upvotes: 4
Views: 5954
Reputation: 386736
document.createTextNode
creates a text node without style. For adding a style to some text, you need to add an element which can have a style
attribute, like <span>
.
Instead of using
li.appendChild(document.createTextNode("Firstname:" + firstname.value + ", Lastname: " + lastname.value ));
you may take another element, like span.
var span = document.createElement('span');
span.style = ...; // apply your style
span.appendChild(document.createTextNode("Firstname: "));
li.appendChild(span);
li.appendChild(document.createTextNode(firstname.value + ", Lastname: " + lastname.value));
ul.appendChild(li);
Upvotes: 4