-1

In an Html file that I have, there is a paragraph tag that basically looks like this:

<p class="col-sm-8 form-control-static wordwrap">
Hey
What's
Up
</p>

The contents of this paragraph are grabbed from a textarea that a user fills out and the value of this textarea is grabbed via jquery and filled into this element. The output looks like this: Hey What's Up

This paragraph tag ignores the newlines within the paragraph, so the paragraph displays all on one line. Due to the format and layout of the project, I can't necessarily change the html source. I was wondering if there was a way to change this exact element to be:

<pre class="col-sm-8 form-control-static wordwrap">
 Hey
 What's
 Up
</pre>

using only javascript. Is this possible? This is so my output will keep the newlines.

2 Answers2

0

I think you are looking for something like this. you tagged jquery so I used that but this could be done in vanilla js too.

I linked to a onkeyup event if you wanted to change to use the button only if you wanted

$(document).ready(function(){

  function updateContent() {
     $('#p1').html($('#source').val());
  }

  $('#update').on('click', function(e){
   updateContent();
   // add other stuff here
   // for only the click event
  })
  
  $('#source').on('keyup', updateContent);


})
button {
  display:block;
}

#source {
  height:100px;
}
#p1{
  white-space:pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="source" placeholder="Update content and click 'update'">new content

add line breaks and <p>html markup</p>
</textarea>
<button id="update" >Update</button>

<p id="p1">THIS WILL CHANGE!</p>
happymacarts
  • 2,547
  • 1
  • 25
  • 33
-2

It is very simple and has been asked before... BUT here it is, using DOM:

document.getElementById("p1").innerHTML = "<p>This</p><p>Has</p><p>Changed!</p>";
<p id="p1">THIS WILL CHANGE!</p>

So your piece of code you need is:

document.getElementById("p1").innerHTML = "New text!";

EDIT

This is simpler, easier and more browser friendly than using <pre> tags. Therefore, I would highly recommend you to use this instead.

Sank6
  • 491
  • 9
  • 28
  • There we go that's better! – Sank6 May 01 '17 at 18:49
  • *"and has been asked before"* then question should be dupe closed. Do you have a duplicate? – Kevin B May 01 '17 at 18:49
  • [Here](http://stackoverflow.com/questions/20918544/replace-html-part-by-javascript) and [here](http://stackoverflow.com/questions/15618470/javascript-replace-html-using-innerhtml). This doesn't end! – Sank6 May 01 '17 at 18:52
  • WHY THE DOWNVOTING. ARE YOU GUYS MAD?? Who downvotes the right and only answer? – Sank6 May 01 '17 at 18:53
  • 2
    i mean... the question specifically asks how to replace a paragraph tag with a preformatted text tag. your answer changes the innerhtml of a paragraph tag and doesn't note why that's better than doing what they wanted to do. – Kevin B May 01 '17 at 18:54