Search code examples
javascripthtmloutput

How to position a JavaScript generated Anchor Tag / Element in an HTML page?


I have a js script that outputs a URL which is used to download a file. (this is just the tail end of a file called data.js script):

const blob = new Blob([csvContent], { type:'text/csv;charset=utf-8,' })
const objUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', objUrl)
link.setAttribute('download', 'export.csv')
link.textContent = 'Export Data'

document.querySelector('body').append(link)

No matter where I put this:

<div>
  <script type="text/javascript">src="data.js"></script>
</div>

It always displays at the top of the page. What am I missing? I am new to JS but my searches lead me to believe that I need create a custom tag or element. Thanks in advance.

I tried this but still no success:

<script>
  blob.innerHTML = `<a>$</a>${objUrl}`;
</script>

Solution

  • You're trying to manipulate the blob object directly, which will not work.

    I'd say append the link element you created in your JavaScript directly into the desired part of your HTML document and it'll show up in the div you set it to.

    const blob = new Blob([csvContent], { type:'text/csv;charset=utf-8,' });
    const objUrl = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', objUrl);
    link.setAttribute('download', 'export.csv');
    link.textContent = 'Export Data';
    

    HTML where you want to append your link.

    const targetElement = document.getElementById('download-link-container');
    

    Append link to the element we found.

    targetElement.appendChild(link);
    

    In your HTML, have a container with an ID you can use as the target.

    <div id="download-link-container">
      <!-- Your link will be injected in this -->
    </div>
    
    <!-- Script tag after the container -->
    <script src="data.js"></script>