Show all <p> lines in a .txt file in a horizontal format instead of vertical using javascript and jquery

I'm attempting to export the content from a div as a .txt file, but all the paragraphs are displaying side by side.

For instance, within the div content, I have the following lines:

<div id="content>
    <p>hello</p>
    <p>How are you</p>
</div>

The desired output in the .txt file should be:

 hello
 How are you

However, the actual output appears as:

 hello How are you

Here is the jsfiddle link for reference: https://jsfiddle.net/j046xfoy/

Answer №1

Opt for using .textContent over .innerText:

  • .innerText shows text as it appears in HTML

  • .textContent displays text as raw textNodes

observe the distinction in the code snippet below:

CODE SNIPPET

/* Styles are for demo purposes */
#text {
  border:1px solid blue;
  float:right;
  padding:0 10px;
}
.as-console-wrapper {
  min-height:100%;
  max-width:55%;
}
<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <div id="text">
    <p>Ying 
      and Yang,</p>
    <p style="visibility:hidden">Black and White</p>
    <p>Evil and Good</p>
  </div>

  <script>
    var text = document.getElementById('text');
    var iText = text.innerText;
    var tContent = text.textContent;
    console.log('innerText: \n' + iText);
    console.log('textContent: \n' + tContent);
  </script>
</body>

</html>

Answer №2

Integrate jQuery into your project.

Here is the HTML snippet:


<div id="content">
  <p>Greetings</p>
  <p>How's everything going?</p>
</div>
<a href="#" id="downloadLink">Download as .txt</a><br>

Below is the JavaScript code:


var root = document.getElementById('content');
var arr = [];
var texts = [].map.call( root.querySelectorAll("p"), function(v){
  return v.textContent || v.innerText || "";
});
for (var i in texts) {
  arr = arr + texts[i];
  arr += "\r\n"; // move to a new line
}
$("#downloadLink").click(function() {
  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:attachment/text,' + encodeURI(arr);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'downloadedFile.txt';
  hiddenElement.click('downloadLink');
});

Access the Fiddle Here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using three.js orbitControl, inputting text into textboxes in a Ruby on Rails application is

My three.js application seems to be causing issues with my text field in my Ruby on Rails application. I am unable to write anything in the text field or even click on it. Does anyone know why this is happening? Here is a snippet of my three.js application ...

What is the best way to assign a Python variable to an <a-assets> element?

There exists a Python function that provides the chosen background <a-sky ID="sky" color="{{object.background}}"></a-sky> The backgrounds can be in the format of '#c6aa99', '#e1a600', '#290942', 'star' ...

What could be causing my CSS navigation toggle button to malfunction?

My attempt at creating a toggle button for tablets and phones seems to be failing. Despite the javascript class being triggered when I click the toggle button, it is not functioning as expected... https://i.stack.imgur.com/j5BN8.png https://i.stack.imgur. ...

Strategies for managing Shopify's API request restrictions with the microapps Node.js module

I've been struggling to find a solution to this problem and I just can't seem to get it right. I'm currently using a Node.js module for the Shopify API created by microapps. In my JSON object, I have a list of product IDs and SKUs that need ...

JSON does not transmit data via post requests

I have a question regarding JSON. Initially, I created this jQuery code: <script> $('#buy').click(function(){ var items=[]; var item={ firstname:'blabla' ...

Managing cookies in PHP and JavaScript can present challenges due to variations in how different browsers

Our website utilizes ExpressionEngine as the CMS and Magento's cart for e-commerce. I am encountering challenges with cookies and their accessibility in various sections. A cookie is used for storing search selections, allowing users to return to our ...

The for loop GET request is not successfully pushing data to MongoDB, leaving the database with no entries

My current challenge lies in transmitting data from my for loop to MongoDB. Upon executing the js file using node initCount.js in the console, no errors are returned and everything seems to be working correctly. However, upon checking my MongoDB backend, I ...

Bootstrap table styling fails to be applied to dynamically generated tables via JavaScript

Hey there, I'm diving into the world of website development for the first time, just getting started a couple of days back. Although I have some experience with Python and C# programming, I'm facing challenges in generating an HTML table using J ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...

What is the best way to fill a "multiselect" element with information from a JSON object?

I'm struggling to populate the multiselect field with data from a JSON object. No matter which multiselect I use, the data shows in inspect mode but not on the frontend. It was supposed to look like this. https://i.sstatic.net/FVz2H.png but it comes ...

Locator for finding compound text within a div class using Selenium WebDriver

I am struggling to select a specific button in the UI that shares similarities with other elements. Below is the code snippet for the button in question: <div class="ui green ok inverted button"> <i class="checkmark icon"></i> Yes </d ...

What is the best way to position elements at the top and bottom of a container?

I'm struggling to align one of the elements in my container to the top while using flexbox. All elements are currently aligned to the bottom, but I want a specific text to be at the top of the container. jQuery(document).ready(function($) { ...

The SVG path is not aligned properly with the container's viewbox dimensions

Recently, I came across an icon provided by a plugin I am using called calendar. However, I wanted to enhance my icons set with a new addition - the twitter icon. svg { display: inline-block; height: 16px; width: 16px; margin: 2px 0; ...

Is it necessary for all elements of a web application to exist as React components?

It's been more than 2 years since I last worked with React, and revisiting my old code has left me feeling a bit confused. If I were to create an Instagram clone, would it be best to use HTML templates and inject JavaScript like this: <div id="rea ...

Programmatically show/hide legend items in amCharts 4

The project includes a Line chart with a legend that are initialized in separate containers. Both components are created using a createFromConfig method. <div ref="chartdiv" /> <div ref="legenddiv" /> My goal is to store to ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

Sending data to a MySQL database using AJAX with PHP

While attempting to use ajax to insert a value in PHP, I am encountering an issue where the data is not getting inserted into the database. The code snippet I am using was sourced from answers provided on this site. Can someone please point out where I m ...

v-for loop to populate dropdown menu with identical values

Recently, I started working on a points counter app using Vue.js and encountered some issues with the v-for loop and dropdown menu functionality. Within my Vue.js application, I have an array of players as shown below: var app = new Vue({ el: '#l ...

Having trouble with the functionality of the AngularJS Custom Service?

I have developed a straightforward service as shown below: var app = angular.module('myApp', ['ngRoute']); app.service('UserService', function() { this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""}; this.ad ...

I'm having trouble with my sticky position in the code. I tried setting it to the left side, but it's not behaving as

While I am delving into Bootstrap, HTML, and CSS to enhance my skills, I have hit a snag. My intention was to make the sidebar sticky but it seems to stubbornly stick to the left instead. Despite attempting to apply "position: sticky" and setting "left: 0" ...