1

I'm trying to append a text node into a paragraph with values taken from its parent function's parameters.

function writeText(id, value, text) {

    //create our html elements

    var body = document.body;
    var par = document.createElement("p");
        par.className = id;
    this.value = document.createTextNode(value);
    this.text = document.createTextNode(text);

    //instantiate array that we will push value and text into

    textToInsert = [];
    textToInsert.push(this.value, this.text);

    //appends this.text and this.value inside the paragraph
    //and then appends that paragraph element into the body

    par.appendChild(textToInsert.join(' :'); //this does not work!
    par.appendChild(this.value+this.text); //this does not work!
    par.appendChild(this.value); //this works!
    body.appendChild(par);       
}

This code is giving me the error message

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

So I take it that join() does not generate nodes. How can I concatenate two variables inside one appendChild()?

discardthis
  • 169
  • 1
  • 6
  • 14

1 Answers1

2

join does always generate strings. Your text nodes in the array will get stringified.

Instead, you will need to put plain strings in your array, and create only a single text node that you can append, with the concatenated content that you want.

var stringsToInsert = [value, text],
    stringToInsert = stringsToInsert.join(' :');

var textNode = document.createTextNode(stringToInsert);
par.appendChild(textNode);     
Bergi
  • 630,263
  • 148
  • 957
  • 1,375