megler
megler

Reputation: 216

Creating text elements in JS

I have a div that is dynamically created in my JS. Everything works except the line breaks. Am I appending them incorrectly?

var reminderDiv = document.getElementById('reminderDiv');

var h2 = document.createElement('h2');
var reminderName = document.createTextNode(item.name);
h2.appendChild(reminderName);

var reminderDetails = document.createElement('p');
var br = document.createElement('br');
var reminderOccasion = document.createTextNode('Occasion: ' + item.occasion);    
var reminderLastGift = document.createTextNode('Last Gift:' + item.lastgift);   
var reminderPrefGift = document.createTextNode('Preferred Gift:' + item.prefgift);
reminderDetails.appendChild(reminderOccasion);
reminderDetails.appendChild(br);
reminderDetails.appendChild(reminderLastGift);
reminderDetails.appendChild(br);
reminderDetails.appendChild(reminderPrefGift);

Upvotes: 2

Views: 53

Answers (2)

Giacky
Giacky

Reputation: 181

The problem with your code is you're inserting the same element over and over again. You should create new <br> tag each time when you will append it.

Upvotes: 0

Quentin
Quentin

Reputation: 943240

Everything works except the line breaks

Line break: Singular.

You only create one. You then append it twice. So it gets appended after reminderOccasion and then again after reminderLastGift (which removes it from its previous position).

Upvotes: 5

Related Questions