Search code examples
javascriptappendchild

javascript appendChild did not work and give me an [obect] result


Running the following code, I get the results like:

[object HTMLHeadingElement]
[object HTMLHeadingElement]
[object HTMLHeadingElement]
[object HTMLHeadingElement] 

But it should have some result of some ul list. I do not know where I am going wrong. What am I missing?

function textContent(ele,value){
    var content = ele.textContent;//check if textContent is defined
    if(value === undefined){//no value passed, so return current text

        if(content !== undefined) return content;
        else return ele.innerText;

    }else{//a value is passed, so set text

        if(content !== undefined)  ele.textContent = value;
        else ele.innerText = value;

    }
}


(function(){
    var titles = document.querySelectorAll('.docHomeDetails h3');
    var sideList = document.getElementsByClassName('sideList')[0];
    var ul = document.querySelectorAll('.sideList ul')[0];


    window.onload = function(){
        for(var i = 0; i< titles.length; i++){

            var  li = document.createElement('li');

            textContent(li, titles[i]);//setting plain text into li element
            ul.appendChild(li);

        }                       
    }

}());

Solution

  • The error is here:

    textContent(li, titles[i]);//setting plain text into li element
    

    You try to assign an element itself not the text inside. Should be:

    textContent(li, titles[i].innerHTML);
    

    My fiddle.