简体   繁体   中英

How to change the innerHTML of the current element?

I am trying to print a text on the current element. I tried these two codes, but they doesn't seem to work:

This one is printing the text in the whole document:

<div>
  <script>
    fetch('file.txt').then((resp) => resp.text()).then(function(data) {
      document.write(data);
    });
  </script>
</div>

Resulting in this:

<html>
  <body>
    <!-- THE TEXT THAT I REQUESTED APPEARS HERE -->
  </body>
</html>

And the code below is returning the following error:

<div>
  <script>
    fetch('file.txt').then((resp) => resp.text()).then(function(data) {
      document.this.innerHTML(data);
    });
  </script>
</div>

Cannot read property 'innerHTML' of undefined

Replace this with body . innerHTML is not a function its a property you need to set it.

I think you want to append to the <div> in which the <script> us present. You can access the script and get its parentNode

<div>
  <script>
    const script = document.scripts[document.scripts.length - 1];
    fetch('file.txt').then((resp) => resp.text()).then(function(data) {
      script.parentNode.innerHTML = data;
    });
  </script>
</div>

Note: document.scripts[document.scripts.length - 1] will get the current <script> tag because it will be lastest script executed.

You can use document.writeln() to write within the current div

<div>
  <script>
    fetch('file.txt').then((resp) => resp.text()).then(function(data) {
      document.writeln(data);
    });
  </script>
</div>

Hre is a similar example demonstrating the result.

 <div> <script> Promise.resolve('abc123<br>xyz789') .then(function(data) { document.writeln(data) }); </script> </div> 

First you should move the script out of the div and then replace 'this' in your code with a reference to the target div.

If you give your div an id of 'target' you could do the following:

const target = document.getElementById('target');

fetch('file.txt').then((resp) => resp.text()).then((data) => target.innerHTML = data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM