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>
How is that even possible?
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.
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', onLoaded, 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', onLoaded, false);
function onLoaded(evt)
{
alert( document.querySelector('#myDiv').innerHTML );
}
</script>
</head>
<body>
<div id='myDiv'>Hello</div></body>
</html>
PHP is a serverside language, it is rendered serverside. This means it won't render if you just open a .php file with a web browser and it won't work if you try to run the code in an online editor. It needs to be hosted by a web server and then the sever renders it when requested.
How is that even possible? Becuase the php is never rendered, therefore the <div> doesn't exist.
That being said, a few other notes:
) php goes in the <body></body> section of your html
) you can put the <script>s at the bottom of the body section and than you don't need to use $(document).ready(), since if you're at the bottom of the <body>, the document is ready...
This won't work in an online editor, but you code should look something like this:
<!doctype html>
<head></head>
<body>
<?php echo "<div id='myDiv'>Hello</div>"; ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
alert($("#myDiv").html());
</script>
</body>
</html>