Reputation:
I'm doing an exercise from javascriptissexy.com, the exercise is to build a quizzer. i'm trying to show a question based on the variable page value, question are stored in array object, when a the next button is clicked the page variable is incremented by 1 and the next question is shown with its choices.
What I want to do is after the next button click, remove the previous appended question and its choices.. how can i do this?
function createQuiz(crPage) {
textNode = Allquestions[indexController].question;
switch (crPage) {
case 0:
$("legend").append(textNode);
appendChoices()
break;
case 1:
$("legend").append(textNode);
appendChoices()
break;
case 2:
$("legend").append(textNode);
appendChoices()
break;
case 3:
$("legend").append(textNode);
appendChoices()
break;
case 4:
$("legend").append(textNode);
appendChoices()
break;
case 5:
$("legend").append(textNode);
appendChoices()
break;
case 6:
$("legend").append(textNode);
appendChoices()
break;
default:
// code
}
}
function appendChoices() {
for (var i = 0; i < Allquestions[indexController].choices.length; i++) {
console.log(Allquestions[indexController].choices[i]);
}
}
Upvotes: 1
Views: 488
Reputation: 32145
Well instead of using .append()
each time, you can use .replaceWith()
over $("legend").children()
.
For example the code in each case will look like this:
$("legend").children().replaceWith(textNode);
appendChoices()
break;
It will replace the $("legend")
content in each case.
Edit:
Or best approach would be to use .html()
method like this:
$("legend").html(textNode);
appendChoices()
break;
Note:
I see that you are doing the same thing in each case, by using the same statements, what's the purpose of the switch
block?
Upvotes: 2
Reputation: 157
Not sure if you use jQuery but; using jQuery empty() function you can easily remove previously added question like:
$('legend').empty();
You can find more information here: jQuery API empty() function
Upvotes: 0