Condomer
Condomer

Reputation: 39

Is it possible to convert html to type node?

I return HTML and I need to append it to the element on page, but its not type node, is it possible to convert it?

generateOptionMonths() method's code was originally in the createCheckpointModalHtml() and everything was working, but the whole code was very complicated so I wanted to do it as a separate method. I don't get it why it is not working, considering it was the exact same code when it was in createCheckpointModalHtml() and it was working fine.

class CheckpointsArea {

   constructor(){
        this.monthsNames = this.generateOptionMonths();
   }

   createCheckpointModalHtml(){
        let chooseMonth = createElement("select", "select-month");
        chooseMonth.appendChild(this.monthsNames);//Error is here
   }

   generateOptionMonths(){
    let monthNames = this.getDaysAndMonth().map( date => {

        let month = createElement("option", "select-option");
        month.innerText = date.Name;

        return month
    });
    }

}

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

Upvotes: 0

Views: 157

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

I can fix your code like so

<html>
    <head></head>
    <body></body>
    <script>
        class CheckpointsArea {
            constructor(){
                this.monthsNames = this.generateOptionMonths();
                console.log(this.monthsNames);
                this.createCheckpointModalHtml();
            }

            getDaysAndMonth() {
                return [{Name: 'foo'}, {Name: 'bar'}];
            }

            createCheckpointModalHtml(){
                let chooseMonth = document.createElement("select", "select-month");
                this.monthsNames.forEach(m => chooseMonth.appendChild(m));
                document.body.appendChild(chooseMonth);
            }

            generateOptionMonths(){
                return this.getDaysAndMonth().map( date => {
                    let month = document.createElement("option", "select-option");
                    month.innerText = date.Name;
                    return month;
                });
            }
        }
        const cp = new CheckpointsArea();
    </script>
</html>

You had 2 main issues.

  1. You were attempting to call appendChild passing an array. Instead loop over the array and append each element.

  2. generateOptionMonths wasnt returning anything. The lambda in the map function was but the function itself was not.

You were also not appending the select element to the document body.

Upvotes: 1

Related Questions