Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text with newline inside a div element is not working

I have a div element

<div id="testResult" style="padding-left: 120px;">

I am trying to print some text with newline character '\n' inside the div element.

But in my html page displayed text is ignoring the newline character.

 $("#testResult").html("Feature: Apply filter to image\n    As an user\n    I want to be able to apply a filter to my image\n    So I can make it look better and match my card's stile\n\n  @US2330 @done\n  Scenario Outline: Apply filter to a picture    # features/card_edit_filter.feature:33\n    Given I am on \"Filters Editor\" screen        # features/step_definitions/common_steps.rb:1\n    And I see my card with the original image    # features/step_definitions/card_filter_steps.rb:21\n    When I touch the \"<filter_name>\" filter      # features/step_definitions/card_filter_steps.rb:1\n    Then I see the image with the filter applied # features/step_definitions/card_filter_steps.rb:26\n\n    Examples: \n      | filter_name   |\n      | Black & White |\n      | Sepia         |\n      | Vintage       |\n\n  @US2330 @done\n  Scenario: Restore image after applying filter  # features/card_edit_filter.feature:47\n")

I want to show the text as:

Feature: Apply filter to image
    As an user
    I want to be able to apply a filter to my image
    So I can make it look better and match my card's stile

  @US2330 @done
  Scenario Outline: Apply filter to a picture    # features/card_edit_filter.feature:33
    Given I am on "Filters Editor" screen        # features/step_definitions/common_steps.rb:1
    And I see my card with the original image    # features/step_definitions/card_filter_steps.rb:21
    When I touch the "<filter_name>" filter      # features/step_definitions/card_filter_steps.rb:1
    Then I see the image with the filter applied # features/step_definitions/card_filter_steps.rb:26

    Examples: 
      | filter_name   |
like image 595
Psl Avatar asked Sep 16 '14 07:09

Psl


3 Answers

Add this css:

#testResult
{
    white-space:pre-wrap;
}

Demo

like image 171
Mohit Kumar Avatar answered Oct 11 '22 19:10

Mohit Kumar


You could try a simple css approach maybe?

#testResult {
   white-space: pre-wrap;
}

This will preserve the \n in your output.

like image 37
Flobbo Avatar answered Oct 11 '22 18:10

Flobbo


To preserve newlines and spaces, you can use a <pre> element:

<pre id="testResult" style="padding-left: 120px;"></pre>

$("#testResult").text("Feature: Apply filter to image\n...e:47\n");

Also note the use of .text() rather than .html(). You should always use .text() unless you have a specific reason to need .html().

like image 31
JLRishe Avatar answered Oct 11 '22 18:10

JLRishe