0

I have this function, which I want to create a container div with two child divs, one being the title of the container and the other one being the content. For some reason, this is NOT working when I test it in jsfiddle.

Also, I would like to know how to append this whole container to a div with a specific class in my html.

var add = function(title, content) {
  var addContainerBody = document.createElement("DIV");
  addContainerBody.className = "c-body";
  var addTitle = document.createElement("DIV");
  var titleText = document.createTextNode(title);
  addTitle.appendChild(titleText);
  addTitle.className = "title";
  var addContent = document.createElement("DIV");
  var contentText = document.createTextNode(content);
  addContent.className = "content";
  addContainerBody.appendChild(addTitle);
  addContainerBody.appendChild(addContent);
  document.body.appendChild(addContainerBody);
};

// Callin it //

add("Title","Text");

As you can see, it outputs only the title, and nothing else. I am probably missing something very obvious. What is the issue here?

Sebastian Olsen
  • 7,528
  • 8
  • 35
  • 78

1 Answers1

2

am probably missing something very obvious.

You're never appending the contentText to the addContent element.

function add(title, content) {
  var addContainerBody = document.createElement("DIV");
  addContainerBody.className = "c-body";

  var addTitle = addContainerBody.appendChild(document.createElement("DIV"));
  addTitle.className = "title";
  addTitle.appendChild(document.createTextNode(title));

  var addContent = addContainerBody.appendChild(document.createElement("DIV"));
  addContent.className = "content";
  addContent.appendChild(document.createTextNode(content));

  document.body.appendChild(addContainerBody);
}

add("Title","Text");

I would like to know how to append this whole container to a div with a specific class in my html.

You can use document.getElementsByClassName or document.querySelector to get the div with that class, and then append to it instead of document.body. But make sure that the element is already available to be selected before executing your code.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164