0

I want to use a <div> inside a <p> so that when I render the code, it should print showing the div. Ex: <p> this is a <div></div> </p> Output: this is a <div><div/>

I've tried the code below, but whenever I input any <> in the field, it ignores it and uses it to style the content.

<input type="text" id="body_text" value="" />
<br />
<input type="text" id="title_text" value="" />
<br />
<button type="button" onclick="myFunction()">Try it</button>

<p id="global-title"></p>
<p id="global-body"></p>

<script>
  // Here the value is stored in new variable x
  function myFunction() {
    var x = document.getElementById("title_text").value;
    document.getElementById("global-title").innerHTML = x;
    var y = document.getElementById("body_text").value;
    document.getElementById("global-body").innerHTML = y;
  }
</script>
5
  • You dont.... the browser will close the p automatically. A div inside a p is invalid HTML
    – Paulie_D
    Commented Jan 30, 2022 at 13:23
  • 1
    I'm not sure I've understood what you want to do. Are you trying to show the angle brackets to the reader?
    – A Haworth
    Commented Jan 30, 2022 at 13:25
  • @AHaworth Yes, I am trying to show the angle brackets with the div inside of it
    – Shagufta
    Commented Jan 30, 2022 at 13:32
  • 1
    @Shagufta that's exactly what I've done below.
    – ruleboy21
    Commented Jan 30, 2022 at 13:33
  • 1
    If you want the angle brackets to become human-text, then HTML-encode them as &lt; and &gt;
    – Paul S.
    Commented Jan 30, 2022 at 13:36

1 Answer 1

1

Use .innerText instead of .innerHTML

// Here the value is stored in new variable x
  function myFunction() {
    var x = document.getElementById("title_text").value;
    document.getElementById("global-title").innerText = x;
    var y = document.getElementById("body_text").value;
    document.getElementById("global-body").innerText = y;
  }
<input type="text" id="body_text" value="" />
<br />
<input type="text" id="title_text" value="" />
<br />
<button type="button" onclick="myFunction()">Try it</button>

<p id="global-title"></p>
<p id="global-body"></p>

Not the answer you're looking for? Browse other questions tagged or ask your own question.