Jordi Z Jordi Z - 4 months ago 5
jQuery Question

Replace dynamically filled HTML element through JavaScript


I'm trying create a button or link which enables the user to download a .json file. This file is dynamic and changes depending on what the user does (outside the scope of the question).

I've created a button, which when clicked, generates a blob and a link to download the .json file. However, when the data changes, a new link is created behind the current link, instead of replacing the current one.

enter image description here


How do I alter my code to just replace the existing link, instead of creating a double?

JS code:

function download_rapport(){
var data = { return; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);

var a = document.createElement('a'); = "backup.json";
a.href = url;
a.textContent = "Download backup.json";


I've tried innerHTML instead of appendChild, but instead of a link, it just returns the link as a string.

HTML code:

<form action="javascript:submitQuery()" id="advancedSearch">
<!-- Modal/Pop-up window -->
<div id="generateReport" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<button onclick="download_rapport()">Generate download</button>
<div id="content_test"></div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Fastfood report</h4>
<div class="modal-body">
<div class="table-responsive" id="test">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

The HTML where the download div is located, see
Generate download


Assuming content_test is a div containing only the links, you can replace appendChild(a) with innerHTML = a.outerHTML

appendChild adds the content passed in the arguments each time it is called.

To replace the content you can use the property innerHTML.

outerHTML on a element returns the HTML code you need to insert in the div.

The last line should look like this:

document.getElementById('content_test').innerHTML = a.outerHTML;