1

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>
  • What did you try so far? And why the restrictions of not using IDs or classes? – Hubert Grzeskowiak Aug 04 '16 at 18:54
  • If you code like this, your application/webpage will become hard to maintain and error-prone BTW. I suggest using a proper templating language or a framework. For a quick'n'dirty hack, you can use document.write and load files using AJAX. – Hubert Grzeskowiak Aug 04 '16 at 18:56
  • Perhaps `$("div>span:firstchild").after("").load("myfile.html")` or `$.get("myFile.html",function(data) { $("").html().inserAfter("div>span:firstchild")})` – mplungjan Aug 04 '16 at 19:00
  • @mplungjan Your solution assumes that there is no other HTML on the page. If that was the case, it would be alright, but we don't know that, and this code might need to be modified if there are changes added to the HTML in the future. Hard to maintain. `document.write` is generally best avoided, but in this case, it's the only way to ensure the content is added in the right spot, regardless of the HTML around it. – blex Aug 04 '16 at 19:15
  • 1
    So use document.write correctly: ` – mplungjan Aug 04 '16 at 19:18
  • 1
    @mplungjan Yup, that's what I would recommend, to avoid browser freeze. (upvoted your answer) – blex Aug 04 '16 at 19:19

3 Answers3

2

Here is a script that does not require delayed document.write or sync Ajax

<script>
  document.write('<span id="inserted"></span>'); // inline so ok
  $(function() { $("#inserted").load("myfile.html") });
<script>

In Plain JS use the xmlhttprequest and innerHTML to avoid sync

mplungjan
  • 169,008
  • 28
  • 173
  • 236
1
<div>
  <span>hi, welcome to the </span>
  <script>
      var xhr = new XMLHttpRequest();
      xhr.open('GET', '/filename.txt', false);
      xhr.send(null);

      if (xhr.readyState === 200)
          document.write(xhr.responseText);
  </script>
  <span> season...</span>
</div>

To get the contents of a file, that's hosted on the same directory of the calling site, use an XMLHttpRequest; as illustrated above.


Also, you'll need to make the request synchronous, in order to document.write the contents of the file at that specific location.

Synchronous XMLHttpRequests

Alex
  • 34,899
  • 5
  • 77
  • 90
  • An Ajax request is asynchronous. AFAIK, using `document.write` after the document is ready will result in the whole page being overwritten. What you could do, however, is `document.write('')` on page load, which will then allow you to know where to place the content once you receive it. – blex Aug 04 '16 at 19:00
  • thought of that after i posted it. i've never tested this. if it does write out-of-order, it'd be placed at the end of the document. it wouldn't "overwrite the entire page." – Alex Aug 04 '16 at 19:01
  • 1
    jQuery is tagged. Why not use it – mplungjan Aug 04 '16 at 19:01
  • 1
    It doesn't work, as @blex said, this results in a blank page with the file content, – Yukatanic45 Aug 04 '16 at 19:02
  • also, `5 lines of vanillajs` > `9 lines of jquery` – Alex Aug 04 '16 at 19:09
  • 5 lines of vanilla JS using sync access and document.write that may or may not wipe the browser in for example IE that could manage to close the document while the request finishes. It smells really bad to me – mplungjan Aug 04 '16 at 19:13
  • @mplungjan not part of the requirement. OP'er specifically stated to not use "IDs or classes." and, they provided the sample markup with the script in the middle of the document. there's likely a reasonably plausible use case for this; which we're not privy too. – Alex Aug 04 '16 at 19:16
  • So use document.write correctly: ` – mplungjan Aug 04 '16 at 19:18
  • that's a better approach, yes. but, you're adding an element and performing a lookup; then inserting the content after it loads. not sure if that's within the requirement. post it as an answer ... – Alex Aug 04 '16 at 19:21
0

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.