Yukatanic45 Yukatanic45 - 4 months ago 12
HTML Question

How to place the content of a file in a div with Javascript?

I would like to place the content of a file inside a

div
, and not using IDs or classes, only with the
script
tag inside the
body
.
This is my code:

<div>
<span>hi, welcome to the </span>
<script>
// This is what I need
</script>
<span> season...</span>
</div>

Answer

You can use jQuery AJAX to load a file and use the document.write() function to place the content in that gap. Code:

<head>
    ...
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>

<body>
    ...
    <div>
        <span>hi, welcome to the&nbsp;</span>
        <script>
            $.ajax({
                async: false, // With this, you wait until the file is loaded
                type: "GET", // If the file is large, use POST instead
                url: "yoururl.txt", // Use the relative URL
                dataType: "text",
                success: function(LoadedFile) {
                    document.write(LoadedFile);
                }
            });
        </script>
        <span>&nbsp;season...</span>
    </div>
    ...
</body>

NOTE: Use the &nbsp; instead of the space " " to force your browser to use them.