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

Viewed 82

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?

2 Answers

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);

Change your function according to this solution:

createParagraph() {
    const paragraph = document.createElement('p');
    document.body.append(paragraph);
    const p = paragraph.appendChild(document.createTextNode(this.text));
    return p;
    }
}

Also don't use var.

Related