skip to Main Content

I need to replace just the text 'Yes, I want to receive News, Discounts and Promotions' to my custom text.

From this:

<p id="woo_ml_subscribe_field">
    <label class="checkbox ">
        <input type="checkbox" name="woo_ml_subscribe" id="woo_ml_subscribe" value="1" class="input-checkbox " checked="checked"> Yes, I want to receive News, Discounts and Promotions
   </label>
</p>

To this:

<p id="woo_ml_subscribe_field">
    <label class="checkbox ">
        <input type="checkbox" name="woo_ml_subscribe" id="woo_ml_subscribe" value="1" class="input-checkbox " checked="checked"> my custom text
   </label>
</p>

I tried with this code but it delete ‘input’ element which is inside the ‘p’ element. The input should remain after the replacement.

var content = $("#woo_ml_subscribe_field label").text().replace(' Yes, I want to receive News, Discounts and Promotions','my custom text')
    $("#woo_ml_subscribe_field label").html(content);

2

Answers


  1. you can find the not empty TEXT_NODE and replace, like:

    $('#woo_ml_subscribe_field label').contents().filter(function() {
        return this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue);
    }).replaceWith('your custom text');
    
    Login or Signup to reply.
  2. Instead of going for a complex jQuery code, you can put the text inside an HTML element like <span> and then you can easily manipulate them.

    $('#woo_ml_subscribe_field label span').text('your custom text');
    

    Working snippet:

    $('#woo_ml_subscribe_field label span').text('your custom text');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <p id="woo_ml_subscribe_field">
      <label class="checkbox ">
            <input type="checkbox" name="woo_ml_subscribe" id="woo_ml_subscribe" value="1" class="input-checkbox " checked="checked"> 
            <span>Yes, I want to receive News, Discounts and Promotions</span>
       </label>
    </p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search