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

0

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
source

4 answers

0

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: ');
$('.price-cash').append(hijo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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
0

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:

.html:

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

.js:

$(document).ready(function() {
    $(".precio_txt").remove()
    $(".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
0

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');

Alternative

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
0

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

$(function(){
  var p = $('.price-cash');
  var c = p.children();
  p.text('NUEVO PRECIO: ');
  p.append(c);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="price-cash">Precio:<strong class="idprecio">$ 0.89</strong></p>

Good luck!

    
answered by 21.11.2018 в 19:01