Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the style of CreateTextNode With JavaScript

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?

like image 276
Mohammed Reda Avatar asked Sep 03 '25 04:09

Mohammed Reda


1 Answers

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);
like image 173
Nina Scholz Avatar answered Sep 05 '25 00:09

Nina Scholz