skip to Main Content

I search the best way to save a source code from a html page in a Javascript variable.
The html source code is loaded with php & mysql and looks like for example this:

<!DOCTYPE html>
<html>
<body>

<h2>HTML Images</h2>
<p>HTML images are defined with the img tag:</p>

<img src="w3schools.jpg" alt="W3" width="104" height="142">

</body>
</html>

If I try to simple save it to a variable

var html        = "<?php echo $my_html; ?>";

I get different errors. For example Uncaught SyntaxError: Unexpected token '<'. I think the reason is that there are quotation marks, line breaks, special chars and so in the the content of $my_html. Of course I can save the html content before to an invisible textarea and take then the content of the textarea to the variable. But is there no other / better way?

2

Answers


  1. You don’t need to set the JavaScript variable independently. document.documentElement.outerHTML; is a reference to the HTML contents.

    var markup = document.documentElement.outerHTML;
    console.log(markup)
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>HTML Images</h2>
    <p>HTML images are defined with the img tag:</p>
    
    <img src="w3schools.jpg" alt="W3" width="104" height="142">
    
    </body>
    </html>
    Login or Signup to reply.
  2. Since you are working with PHP, I would recommend using a native function prior to setting the JS variable.
    Have you tried addslashes()?

    <!DOCTYPE html>
    <html>
    <body>
    
      <?php 
        $str = addslashes('What does "yolo" mean?');
        echo($str); 
      ?> 
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search