2

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);
1
  • You only have a single BR element here. appendChild doesn’t clone nodes, it removes the node from its current document position first. Commented Apr 9, 2018 at 14:54

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That makes total sense. If I want multiple breaks, is there a cleaner way to do it than 3 variables each creating a line break?
Reuse the same variable (but assign it a new value!) or don't use a variable at all.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.