1

So, I have a script with both HTML and javascript inside:

<script>
  <br>
  window.onload = myFunction;
  <br>
  function myFunction() {
    // Do something
  }
  <br>
</script>

Obviously, the HTML dont work, but can I remove the HTML tags in scripts somehow? With the javascript code still working. (and not by just going into the code and removing the HTML myself). Is there a way to make the HTML go away or be invisible to the script?

(I've tried just commenting it out with the "< ! - -" and "- - >" but it doesn't work)

Edit: the reason I'm wondering is because I have a weird coding teacher... and he told me you could do stuff like that but I can't get it to work. So I just want to know if it's actually possible.

NitroFray
  • 43
  • 7
  • So my guess is that you have a script that doesn't work either. This is neither valid JS or valid HTML, this is a mess. – Havenard Nov 07 '18 at 19:26
  • to comment stuff out in js you use `//`, `` is for html – Patrick Evans Nov 07 '18 at 19:26
  • 6
    You should do whatever it takes to... avoid everything thats happening here. – The Dembinski Nov 07 '18 at 19:26
  • 1
    The commenting doesn't work because those are HTML comments not JavaScript comments and you're in a `script` tag. Semantically speaking, this is wrong on many levels. What would be the reason for not wanting to edit the original source and instead provide a hack to make this work?... – War10ck Nov 07 '18 at 19:27
  • 2
    In JS, you can comment out a line using `//` and multiple lines using `/* */`. – HynekS Nov 07 '18 at 19:27
  • HTML comments _do_ work in Javascript. It isn't a great solution, but saying they are not valid is incorrect. They are valid for legacy reasons and do not throw errors.. – rlemon Nov 07 '18 at 19:35
  • 1
    @rlemon good point, see here for more information - https://stackoverflow.com/q/808816/864233 - and the W3C Spec - https://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3.2 – romellem Nov 07 '18 at 19:36
  • Are you asking if you can do this without actually editing the script, but make it happen automatically when you load the page? – Barmar Nov 07 '18 at 19:38
  • Well, thank you all for explaining. I finally understand now... this website is alot more helpful than my teacher. Do I do anything with this post now that I've gotten my answer? Delete it? Or just leave it like this? – NitroFray Nov 07 '18 at 19:44
  • If the question has become moot, you can delete it. Or if you think you've figured out the solution from the comments, you can post an answer below. – Barmar Nov 07 '18 at 19:53

1 Answers1

0

Commenting the code using javascript comment tags /*

<script>
/*  
 <br>
  window.onload = myFunction;
 <br> 
*/
  function myFunction() {
    // Do something
  }
  <br>
</script>