Update the text inside a paragraph using jQuery

When attempting to modify two values within a paragraph using jQuery, I encountered an issue where only one value was successfully updated, leaving the other empty.

<div class="container">
<p class="lead custom_bg" id="comment"> updateme!
    <code id="source"> updateme2!</code>
</p>
</div>

Utilizing jQuery ajax

success: function(response){
         $('#comment').text(response['comment']);
         $('#source').text(response['source']);
     }

From my perspective, it appears that the .text attribute modifies all text within the specified paragraph.

Answer №1

The problem arises when you set the text() of the #comment, as it removes all the HTML content within that element, causing the #source to disappear.

To solve this issue, you should update the value of the first text node within #comment specifically, like so:

var response = {
  comment: 'updated comment',
  source: 'updated source'
}

$('#comment').contents()[0].nodeValue = response['comment'];
$('#source').text(response['source']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <p class="lead custom_bg" id="comment"> updateme!
    <code id="source"> updateme2!</code>
  </p>
</div>

Alternatively, you can enclose the desired text in a separate span for direct targeting, like this:

var response = {
  comment: 'updated comment',
  source: 'updated source'
}

$('#comment span').text(response['comment']);
$('#source').text(response['source']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <p class="lead custom_bg" id="comment"> 
    <span>updateme!</span>
    <code id="source"> updateme2!</code>
  </p>
</div>

Answer №2

Implement this to instantly generate the necessary element in the following line

$('#comment').html(response['comment']+'<code id="source"></code>');         
$('#source').html(response['source']);

Updated: .text() changed to .html()

Answer №3

To prevent the destruction of HTML content when setting text, one workaround is to store the inner HTML (e.g., #source) and re-append it after setting the text.

In this example, I have substituted the response section with placeholder text, so you will need to add back the variables accordingly.

var keepMe = $('#source');
$('#comment').text("hello");
$('#comment').append(keepMe);
$('#source').text("hello again!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<p class="lead custom_bg" id="comment"> update me!
    <span id="source"> update me too!</span>
</p>
</div>

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

The jQuery .animate function seems to be malfunctioning

I recently came across this jsfiddle link: http://jsfiddle.net/2mRMr/3/ However, the code provided is not functioning as expected: setInterval(function () { box.animate({ left: function (i, v) { return newv(v, 37, 39); }, ...

Removing an object in Three.js using scene.getObjectByName() method

When developing my game, I encountered a challenge. I'm loading 4 different buildings and creating 15 clones of each within a for loop. These clones are then added to an array called masterBuildingArray, which I iterate through using a forEach loop. T ...

What is the process for retrieving a value from a Django view?

Would it be feasible to call a view from a JavaScript file using Ajax and have the view only return a specific value known as "this"? However, despite attempting this, an error occurs stating that the view did not provide an HttpResponse object, but instea ...

Guide on how to use JavaScript to upload media stream recorder blobs onto YouTube using the YouTube API

Using mediastreamrecorder.js, I am successfully recording video in 5-second blobs within the ondataavailable function. Here is an example of the code: mediaRecorder.ondataavailable = function(blob) { blob=blob; }; While I am a ...

What is the method for updating the inner html of an image tag in HTML?

Displayed below is the current output: <img width="1080" height="1080" src="/image.jpg" class="post-image" alt="image" /> In order to change it, I must replace src with data: <img width="1080" height="1080" data="/image.jpg" class="post-image" ...

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

Tips for incorporating tabs using jQuery

Check out this code snippet: <script> $(function() { $("#tabs").tabs({ event: "mouseover" }); $("#tabs").tabs("add","#tab-4","Friends Discussions"); $("#tabs").tabs("add","#tab-5","Announcements"); $("#tab ...

How can I receive the response from a GET request using React Query? I am currently only able to get the response

I have created a search component where I input a name in the request, receive a response, and display it immediately. However, after the first input submit, I get undefined in response. Only after the second submit do I get the desired response. The tec ...

Is there a term in JavaScript that denotes an object that can be serialized into JSON format?

Can you help me find a term for basic objects that accentuates their simplicity? Particularly, objects that do not reference themselves and do not have any methods or bindings (i.e. JSON-serializable). The terms I am currently using are: "flat object" " ...

Creating an array in Javascript and populating it with dynamically generated values

I am currently iterating through 3 arrays, searching for 'actionTimings' in each array and summing up the values of actionTimings (which are all numbers). How can I store these 3 values in a new array? This is what I have tried so far... $.each( ...

Is it possible to include a link at the conclusion of an Angular Material autocomplete input field?

I'm currently working on adding a persistent link at the end of an Angular Material autocomplete. I want the link to always be visible, even after a search is performed. To achieve this, I came up with a workaround involving a directive that manipulat ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

Error encountered while trying to call callback functions

I encountered an error in my code, but I managed to resolve it independently. Could someone please provide an explanation of why the code wasn't working and delve into the mechanics behind the issue? Here is the code snippet: var listTables = functi ...

Avoid having #content overlap by using a double sidebar layout

My current project involves utilizing Bootstrap to design a webpage featuring two fixed sidebars and a footer. Although I have successfully positioned the sidebars and footer, I am encountering issues with preventing the #content section from overlapping t ...

What is the best way to showcase the chosen items in a dropdown menu?

There seems to be an issue with the selected item not appearing in the input field. export default function BasicSelect() { const [sortBy, setSortBy] = useState(""); const [condition, setCondition] = useState(""); const [delivery, ...

What is the procedure to alter the color of XYChart in JavaFx?

How can I change the color of a bar chart? Does anyone have any tips on: How to adjust the color of line charts? How to assign a CSS class to series? public class CustomBarChart extends Application { @Override public void start(Stage stage) throws Ex ...

Trouble generating document with Firebase setDoc()

In my current project, I am successfully creating a new user with authentication and then using the generated UID to create a new document. Here is the code snippet: const currentUser = await auth.createUserWithEmailAndPassword(email, pass); consol ...

The combination of Asp.net and Bootstrap offers a powerful

I am facing an issue with using Bootstrap in my ASP.NET project. The page displays correctly on a desktop, but when I resize the page to mobile phone size, the navigation panel does not stay in dropdown position. Here is my code: <%@ Page Language="C ...