3

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>
2
  • 1
    Not in the way you've shown. The content of script tags are executed as a JavaScript Program, and the contents of those will throw syntax errors because if(someCondition) { is not a valid program. Commented Dec 24, 2011 at 10:21
  • Its not possible. However, you can use document.write. Commented Dec 24, 2011 at 10:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.