Change the text of a p-label with jquery without affecting its child element


A query that may be easy, I want to change the text of a "p" element but without affecting its child element, that is, its element must be intact.

<p class="price-cash" >Precio:<strong class="idprecio">$ 0.89</strong></p>

What I want is that instead of "Price" another text appears, but without affecting the child element. I tried to do with jquery, but it replaces everything and the elementary son is deleted

$(".price-cash").text('VALOR NUEVO');
asked by Edison Cobos 21.11.2018 в 18:23

4 answers


I think there is no direct way to do it. But I can think of a little trick to simulate the result.

var hijo = $('.idprecio').clone();
$('.price-cash').text('Nuevo texto: ');
<script src=""></script>
<p class="price-cash" >Precio:<strong class="idprecio">$ 0.89</strong></p>

Using the function clone() I make a "copy" of the element I want to preserve before adding the new text to <p> (because it would effectively crush the <strong> child) and finally I hang the father again the child element .

answered by 21.11.2018 в 18:40

The .append() function allows you to insert elements into the DOM. Test as follows:

$(".price-cash").text('VALOR NUEVO ').append("<strong>$0.80</strong>")

In your specific case you could do it in the following way:


     <p class="price-cash">
        <span class="precio_txt">Precio</span>
         <strong class="idprecio">$0.89</strong>


$(document).ready(function() {
    $(".idprecio").before('VALOR NUEVO ')

I encourage you to consult the official documentation of Jquery ( link ) to know more details of this and other functions.

If the answer helped you remember to accept it.

answered by 21.11.2018 в 18:34

You can enclose the word you want to change in a span :

<p class="price-cash"><span>Precio:</span><strong class="idprecio">$ 0.89</strong></p>

And so you can change its content without modifying the other element:

$(".price-cash > span").text('VALOR NUEVO');


As you commented that you had no control over the html, you can try this solution with pure javascript:

var etiqueta = document.getElementsByClassName("price-cash")[0]; // Primer elemento con la clase price-cash
var texto = etiqueta.childNodes[0]; // El primer nodo 'hijo' de la etiqueta p
texto.nodeValue = 'VALOR NUEVO';
answered by 21.11.2018 в 18:46

You can do something like this: to change the text and add the child elements again.

  var p = $('.price-cash');
  var c = p.children();
  p.text('NUEVO PRECIO: ');
<script src=""></script>
<p class="price-cash">Precio:<strong class="idprecio">$ 0.89</strong></p>

Good luck!

answered by 21.11.2018 в 19:01