JavaScript Passing retrieving and passing input info nodeValue vs createTextNode

783 Views Asked by At

I've encountered something I believe is strange in JavaScript. I am building a form the idea of which is to provide the ability to add table rows and fields on demand. As you could imagine I started experimenting with createElement, appendChild, etc.

Why when I try to pass a value from an input field it cannot be appended directly and output to a div tag? However, when passing the retrieved value first through createTextNode and then outputting it works.

The console says that the concatenation pat.appendChild(al) is not an object

but pat.appendChild(text) works fine?

<script type="text/javascript">

function appendTr (){

    var pat = document.createElement("p");
    /*var formValue = document.createTextNode("This works, but why doesn\'t the other one");
    p.appendChild(formValue);*/
    var al = document.getElementById("position").value;
    var text = document.createTextNode(al);
    pat.appendChild(text);
    document.getElementById("outer").appendChild(pat);
}

</script>
<form>
    <table id="job">
        <tr>
            <td><input id="y1" name="y1" type="text"></td>
            <td><input id="y2" name="y2" type="text"></td>
            <td><input id="position" name="position" type="text"></td>
            <td><input id="org" name="org" type="text"></td>
            <td><input class="button" id="addRow" type="button" value="+" onclick="appendTr()"></td>
            </tr>
    </table>

</form>
<div id="outer">Not</div>
1

There are 1 best solutions below

0
jayms On

al is a string and text is a node. The argument of appendChild has to be a node.

To output al directly into a div do something like this:

document.getElementById("outer").textContent=al;

Or when you want html-code in al to work:

document.getElementById("outer").innerHTML=al;