How can I add text to the div without removing the span tag, I have tried two ways and I can't add the text without removing the span.
let message = document.querySelector(".message");
// REMUEVE LA ETIQUETA SPAN
//message.innerText = "Continuar";
// AÑADE EL TEXTO DESPUES DEL SPAN
//message.innerText += "Continuar";
<div class="message">Cambiar texto<span>-></span></div>
You can use the innerHTML property instead of innerText, and thus preserve the span
Analyzing the element with the message class I see that it is composed of two child nodes:
therefore, if we target the first one using the childNodes reading property and its index number ( 0 in this case), combined with the textContent property, then the second (the span) remains unchanged.
Example:
Another solution to this specific case
Analyzing the element again, I see that, in this case, we can also use the firstChild property, since this appears in its structure:
therefore, it would also work like this:
An option that would also give you independence of the text from the second span is to use 2 spans, which are inline elements, this would allow you to use different labels, different formats, very easily.
Staying in HTML:
Staying in JS:
The problem is that innerText or innerHTML overrides the content of the parent div which is the captured element.
Laboratory Notes:
This replaces the entire content of the div, so the
<span>
.This is the content that has that is the text + span + "Continue", since a += b in this case acts the same as a = a + b
Keep in mind that when using a class in the querySelector it will only bring you the first element with that class, if you want it to affect several elements you must use querySelectorAll, which returns an array that you can later go through and do what you want with each element in each iteration.
In case the goal is to select a single element, an alternative could be to select by id using querySelector("#id") or getElementById("id").