Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP-like static html completion in JavaScript?

is it possible to achive similiar results in JavaScript ? My aim is to not write static html within string literals.

<?php
    if (someCondition) {
?>
I'm here, because PHP allows it.
<?php
    }
?>

For example:

<script>
    if (someCondition) {
</script>
I'm here, because JavaScript allows it.
<script>
    }
</script>

I am aware of the following solution:

<p id = "variable">I'm here, because JavaScript allows it.</p>
<script>
    var p = document.getElementById('variable');
    if (!someCondition) {
        p.parentNode.removeChild(p);
    }
</script>
like image 235
Niklas R Avatar asked Sep 26 '26 12:09

Niklas R


1 Answers

Nice thought, but it's not possible in the way you want it.

Every <script> element is evaluated as a JavaScript independent program, which will throw a syntax error in your case.

You'll have to generate the <p> element inside of your JavaScript.

like image 84
Madara's Ghost Avatar answered Sep 28 '26 01:09

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!