Search code examples
javascripthtmlinnerhtmlappendchild

how to append a string with appendChild in javascript


I need to load some data and insert it in two ways into an li. First, it is inserted as a <p>. Second,it is inserted as a hidden input with the value specified. How can I do that? I mean, if I do it with the innerHTML property it works, but I need to add 2 elements, no only one. And when I try to use the appendChild it gives the error:

infoPersonal.js:22 Uncaught (in promise) TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

what can I do?

EDIT: in the code below it only enters if the condition is met, but it is supossed to add the input with every el

const datos= () => {
    const token = localStorage.getItem('token')
    if (token) {
        return fetch('https://janfa.gharsnull.now.sh/api/auth/me', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                authorization : token,
            },
        })
        .then( x => x.json())
        .then( user =>{
            const datalist = document.querySelectorAll(".data")

            datalist.forEach( function(el){
                var input
                const template = '<p>' + user[el.getAttribute("data-target")] + '</p>'
                if (el.getAttribute("data-target")==="birth") {
                    input = `<input class="input-date" type ="date" value="${user[date]}" hidden>`
                }
                el.innerHTML=template //this works
                el.appendChild(input) //this doesn't

            })
        })
    }
} 

window.onload=() =>{
    datos()
}

Solution

  • appendChild expects a Node or element. You have two options:

    Create the element:

    input=document.createElement("input");
    input.type="date";
    input.className="input-date";
    input.value=user.date;
    input.hidden=true;
    

    Or use innerHTML. Of course it will replace the contents of el, but you could use a placeholder or dummy element.

    var div=document.createElement("div");
    div.innerHTML="<input ...";
    input=div.children[0];
    

    I'd do the first thing. Or use a framework if you want to write less, but it's a little overkill just for this.