Ways to insert a line break using ajax

document.getElementById("msg").innerHTML += "<strike>b:</strike> "+ msgs[i].childNodes[1].firstChild.nodeValue;

After retrieving the messages, I noticed that they are all displayed close to each other. Is there a way to display each message on its own line?

Answer №1

Creating a line break in HTML can be done by using the <br /> tag or enclosing content within <p> tags.

Answer №2

To ensure there is a line break after each message within the div, simply include a <br/> tag right after each line added in your function. Just attach it at the end of the line being inserted. For example,

"<b>Message:</b> " + msgs[i].childNodes[1].firstChild.nodeValue;

will now appear as

"<b>Message:</b> " + msgs[i].childNodes[1].firstChild.nodeValue + "<br/>";

After modifying the innerHTML of the div, every change will automatically have a line break following it.

The entire function will resemble this:

if(xhr) {
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if(xhr.status === 200) {
                var value = xhr.responseXML;
                var msgs = value.getElementsByTagName('message');
                console.log("Processing ", msgs.length, "messages");

                for(var i = 0; i < msgs.length; i++) {
                    var id = parseInt(msgs[i].getAttribute("id"));
                    if(lastid < id) {
                        lastid = id;
                    }
                    document.getElementById("msg").innerHTML += "<b>Message:</b> "
                        + msgs[i].childNodes[1].firstChild.nodeValue
                        + "<br/>" // REMEMBER TO INCLUDE BR TAG
                        + "\n";   // Additional newline added for readability
                                  // Helpful when logging/alerting the actual HTML
                }
            }
        }
    }
}

This will append lines of HTML to the div like so:

<b>Message:</b> message 1<br/>
<b>Message:</b> message 2<br/>
<b>Message:</b> message 3<br/>
...

When rendered in the browser, it will display as follows:

Message: message 1
Message: message 2
Message: message 3
...

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

Troubleshooting: Why isn't data being returned from jQuery Ajax request?

I have a set of buttons that I want to click individually. Each time I click one, I need it to send data to a processing page and then return the processed data back to the same HTML while changing the class from "click" to "more." However, my code doesn& ...

Is there a way to upload an image without utilizing or concealing the `<input type='file' />` element?

Currently, I am developing a PHP script that retrieves the directories and files from specified local computer drives. The goal I am striving for is to enable users to upload an image to my server by clicking on its name from the listing, without using th ...

Launch a dialogue box by clicking on the buttons corresponding to the article ID

I am currently in the process of setting up an admin panel with some quick actions for managing my articles, such as deleting them. When I click on the trash can icon, a dialog box should open and prompt me to confirm the deletion. This dialog box should b ...

What's the best way to vertically center a div with a 100% width and a set padding-bottom on the screen?

I am struggling with positioning the following div on my webpage. .div { width:100%; padding-bottom:20%; background-color:blue; } <div class="div"></div> I have been searching for a solution to vertically center this responsive div on my web ...

Adding text to an existing div element using jQuery and ensuring the div tag automatically adjusts its height according to the text length

I have attempted to implement the following code, but unfortunately, it is not functioning as expected. I am hopeful that someone can assist me. I am seeking a way for the div tag to dynamically increase its height based on the size of the text. Does any ...

Utilizing next/image as a backgroundImage in a div container

Currently, I am working with nextjs and I am trying to set a background Image for a specific div using next/image. Most of the sources I found only explain how to implement full screen background images with next/image, not for a single div. I stumbled upo ...

Troubleshooting Yeoman and Angular: Routing troubles persist

I recently started exploring with yeoman to develop angular applications. I am facing an issue while trying to create routes using yo:angular route. After running the command: yo:angular route foo yeoman generates the following files: app/scripts/contr ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed: The issue highlighted in red is that I want to show the Index of each JSON array as the Table number. Below is the code snippet: function getExternal() { fetch('https://kyoala ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

What measures can be taken to prohibit a user from accessing a client-side HTML file using express?

I am currently developing a task management application called "todolist." In my node.js code, I utilize express and grant it access to my directory named Client: var app = express(); app.use(express.static(__dirname + "/Client")); The contents of my Cl ...

The memory usage steadily increases when you refresh data using the anychart gantt chart

I have a basic anychart code to update a gantt chart every second: function initializeSchedule(){ anychart.onDocumentReady(function () { anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) { documen ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

The issue of duplicated elements arises when Ajax is utilized within Django

Upon form submission, a Graph is generated using Plotly. Utilizing Ajax to submit the form without refreshing the page results in duplicating the form div on the screen. How can this issue be resolved? The code snippet below showcases my implementation wit ...

Tips on accessing information from a JSON file

I am facing an issue while trying to extract data from a JSON object that was passed from the servlet. The keys in my JSON object are numbered, and I need to append these numbers to the names of the keys. The structure of my response is as follows: {"sha ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Update the Material-UI theme to a personalized design

I am currently using Material-UI in my React project. However, I'm facing some difficulties in applying a theme globally. Up until now, I have only managed to apply the theme to individual components like this: import { MuiThemeProvider, createMuiTh ...

Having trouble with the sleep function in nodejs?

Hey there! I'm currently working on a Node.js function that sends requests using array.map. However, I'm facing a challenge with making the function wait for 4 minutes when an error occurs before sending the next request. I've attempted to u ...

Effortlessly add and manipulate multiple classes in a generic class using querySelectorAll and classList, eliminating the

I'm encountering an issue that requires me to repeatedly utilize querySelectorAll with Element.classList. Each time, I must convert the NodeList obtained from Element.querySelectorAll into an Array. Then, I need to iterate over the Array using a for ...

Broadening the capabilities of jQuery through a versatile function

Currently, I am in the process of developing a generic function for my website using jQuery that will be utilized across the entire site to display success or error messages. After careful consideration, I have decided to transform this function into a plu ...