Your attempt is almost correct. Of course, for example window[1029376]
is not a valid object property of window
.
As long as your PHP output is JavaScript syntax it will work.
If your code has the purpose to select a random element (as unrealistic as that is), use document.getElementById() for IDs or the other getElementBy... functions.
<?php
$dynamicHTMLElementId = rand();
?>
<script type="text/javascript">
var dynamicHTMLElement = document.getElementById('<?php echo json_encode($dynamicHTMLElementId); ?>');
</script>
This may result in (with the ID being random):
<script type="text/javascript">
var dynamicHTMLElement = document.getElementById('1335407484');
</script>
Simply look at the source code of the output and check the browser console for errors.
Be aware that json_encode
will not output quotes for a number.