Why is my class Paragraph not making a paragraph element <p>a</p> in JavaScript?

Precent John :

I have the following piece of code in JS:

class Paragraph {
  constructor(text) {
    this.text = text;
    this.createParagraph();
  }
  createParagraph() {
    var paragraph = document.createElement('p');
    var p = paragraph.appendChild(document.createTextNode(this.text));
    return p;
  }
}

var a = new Paragraph("a"); // <p>a</p> This is the result I want, which I'm  not getting
console.dir(a);

I want to be able to create what I've described above through var a = new Paragraph("a"); but it isn't working, can anyone help out why?

Rory McCrossan :

There's two issues. Firstly createParagraph() needs to return the paragraph, not p as that contains the appended child element, in this case that's the text node.

Secondly the constructor needs to return the p you created in createParagraph(). Try this:

class Paragraph {
  constructor(text) {
    this.text = text;
    return this.createParagraph();
  }
  createParagraph() {
    var paragraph = document.createElement('p');
    paragraph.appendChild(document.createTextNode(this.text));
    return paragraph;
  }
}

var newPara = new Paragraph("Lorem ipsum");
document.body.appendChild(newPara);
console.dir(newPara);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29690&siteId=1