$("#qid").text(str); rewrites the content of qid with the text you pass it.
The content of qid includes the span with the qrtr_id so when you rewrite it you destroy that span.
$("#qrtr_id") then doesn’t find any element.
Wrap Some random text here : in another span and target that instead of qid.
Solution 2 :
First of all do not mix jquery and vanilla javascript, please :).
Second, the main problem is that you are using the .text(text) method. This will replace all content inside the target element, so your second span will not exist anymore. This will replace the innerHTML with the text.
So my suggestion is to use the append method to add your last span inside the first one.
// the main span
const $firstSpan = $('#id');
// add the whole text, except the last word into the main span
const $firstSpan.text(arr.slice(0, arr.length-1).join(' '));
// create a span do wrapp the last word
const $lastWord = $('<span>');
// add the last word into the correspondent span
$lastWord.text(arr[arr.length-1]);
// add the last word span into the main span
$($lastWord).appendTo($firstSpan);
Solution 3 :
As I can see, use <= in for loop as below.
for(var i=0; I <= arr.length-1; i++)
OR, use <arr.length in for loop as below.
for(var i=0; I <= arr.length; i++)
Problem :
I am trying to print the response received from my AJAX call to my PHP script. This is my code:
<span id="qid" style="display: none;">
Some random text here :
<span id="qrtr_id" style="color: crimson;"></span>
</span>
All I am trying to do, is split the response and print a part of the response (excluding the last word) in a separate <span> and the last word in a separate <span>. But the last word never gets printed, although when I console.log() the word, then it shows correctly.
I’ve re-checked my <span> ids and they are correct too. Where am I going wrong?
Comments
Comment posted by How can I change an element’s text without changing its child elements?
Does this answer your question?
Comment posted by freedomn-m
I’ve reformatted your code to make the html nesting more obvious.
Comment posted by Quentin
@Lubji — Well, that won’t work, so do what I said instead.
Comment posted by freedomn-m
To be explicit:
Comment posted by Ricardo Ferreira
Sorry, I have sent before I finish writing the code.
Comment posted by Ricardo Ferreira
You only need to recreate the last span. Or you can make the last span a sibling of the first one, instead of a child.