1

I was making a quiz site and when I came to the point when I was making a button to show you the correct answer of your mistake I used document.getElementById but it always erased the rest of the answers that was written by the same method.

here is a snippet of my javascript code

if (mistakes > 0) {
  if (document.getElementById('wrongAnswer1').checked === true || 
      document.getElementById('wrongAnswer2').checked === true) {
        document.getElementById('mistakesDiv').innerHTML =
          document.getElementById('mistakesDiv').innerHTML + 
          "<br>" + 
          "question 1's correct answer is" + 
          document.getElementById('correctAnswer1').value;
   }
}

3 Answers3

1

Design your html div as:

<div id="contentId">
 ......
 ......
</div>

And your javascript like:

var div = document.getElementById('contentId');
div.innerHTML += 'your content';
agrm
  • 3,735
  • 4
  • 26
  • 36
Sunny
  • 577
  • 6
  • 20
0

You can separate the content which you are adding dynamically from existing content because when you are updating innerHTML it will update all the content inside the selected element. So one solution is take a parent div(the div which you will select for adding new child) and add child divs(dynamically added div) inside that for each correct answer. If you want to give some id to dynamic div you can use a counter or question id for which this new child div has got added. For adding new children to "parent" you can use "appendChild" method. It will be something like this:

<div id="parent">
  <div id="child1">Here goes the correct answer</div>(button element will also work fine)
</div>

I have created a fiddle for your scenario please have a look: https://jsfiddle.net/jbw7ku15/

0

In order to append without changing the actual html, for example you want to give the user the ability to add fields to a form that he is in process of filling. You can use insertAdjacentHTML

var html = "<br>" + "question 1's correct answer is" + document.getElementById('correctAnswer1').value;
document.getElementById('mistakesDiv').insertAdjacentHTML("afterend",html);
lisandro
  • 454
  • 4
  • 12