user7554677
user7554677

Reputation:

Failed to AppendChild -- trying to make one method append another in a different class

The code below gives me the following message in the console:

Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent

The render method of the first class is supposed to create an unordered list for which there is a child ordered list (in the Counter.render method), which has direct children.

    class CounterList {
  constructor(){
   this.counters = [];
  }
  addNewCounter(counter) {
    this.counters.push(this.Counter);
  }
  render() {
    var $ul = $('body').append("<ul></ul>");
    $ul.append(Counter.render);
    return $ul;

  }
}

class Counter {
  constructor() {
    this.name = $("#new-counter-name").val();
    var count = 0;
  }
  decrement() {
    this.count--;
    renderPage();
  }
  increment() {
    this.count++;
    renderPage();
  }
  render() {
    var li = '<li><span>'+this.name+'</span><button>'+this.decrement+'</button><span>'+this.count+'</span><button>'+this.increment+'</button></li>';
    return li;

  }
}

EDIT: I realized I only get this error with the return $ul. Otherwise, no errors, but nothing happens.

Upvotes: 0

Views: 39

Answers (1)

Kosh
Kosh

Reputation: 18423

When you do var $ul = $('body').append("<ul></ul>");

Your $ul is body.

You have to do:

var $ul = $('<ul/>').appendTo('body');

Upvotes: 1

Related Questions