Home > Mobile >  Javascript cannot reach element loaded with php
Javascript cannot reach element loaded with php

Time:11-04

I load div with PHP and then I want to get it from HTML using Javascript. Getting element by id alerts undefined.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
   <?php echo "<div id='myDiv'>Hello</div>" ?>
     <script>
      $( document ).ready(function() {
        alert( $("#myDiv").html())
    });
    </script>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How is that even possible?

CodePudding user response:

You have saved the file with a .htm extension. Change it to .php and the code works as expected.

With HTML

<?php echo "<div id='myDiv'>Hello</div>" ?>

is interpreted as:

<?php echo "<div id='myDiv'>
Hello
</div>
" ?>

with lines 1 and 3 seen as tags, and the other two as output.

CodePudding user response:

The following code exists inside "c:\xampp\htdocs\snippets\nov21\something.php" and when requested as localhost/snippets/nov21/something.php (the web-root directory is c:\xampp\htdocs\ ), performs the action you've mentioned.

<!doctype html>
<html>
<head>
<script>
window.addEventListener('load', onl oaded, false);
function onLoaded(evt)
{
    alert( document.querySelector('#myDiv').innerHTML );
}
</script>
</head>
<body>
    <?php echo("<div id='myDiv'>Hello</div>"); ?>
</body>
</html>

Viewing the page-source in the browser returns the following:

<!doctype html>
<html>
<head>
<script>
window.addEventListener('load', onl oaded, false);
function onLoaded(evt)
{
    alert( document.querySelector('#myDiv').innerHTML );
}
</script>
</head>
<body>
    <div id='myDiv'>Hello</div></body>
</html>
  • Related