[SOLVED] Replace only text within multiple divs using jquery

Issue

This Content is from Stack Overflow. Question asked by Lenin Zapata

I can’t replace text inside Div or Containers. I just want to replace the text but it doesn’t work for me. I’ve tried several ways but it still doesn’t work.

I just want to replace the “-” with empty “”. But it should just be the text without overriding the tag classes.

<div class="reemplazo-guion">
  <div class="kt-btn-wrap kt-btn-wrap-0">
   <a class="kt-button" href="#" style="border-radius:10px;border-width:1px" >
     <span class="kt-btn-inner-text">Accede Ahora al Método <strong><em>G-e-n-g-h-i-s K-h-a-n</em></strong></span>
   </a>
  </div>
</div>


jQuery(document).ready(function(){
jQuery('.reemplazo-guion').contents().filter(function() {
      return this.nodeType == 3;
    }).each(function(){
      this.textContent = this.textContent.replace('-','');
    });
});

Code: https://jsfiddle.net/xpcf49mh



Solution

It looks like in order to get all the text nodes within .reemplazo-guion you will need to add a * to the selector (resulting in ".reemplazo-guion *") as .contents() will only pick up the direct children of the jQuery-selected element(s). With the * wildcard all "-"s can now be found and replaced by blanks:

jQuery(document).ready(function(){
jQuery('.reemplazo-guion *').contents().filter(function() {
  return this.nodeType == 3;
}).each(function(){
  this.textContent = this.textContent.replaceAll('-','');
});
});
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<div class="reemplazo-guion">
  <div class="kt-btn-wrap kt-btn-wrap-0">
   <a class="kt-button" href="#" style="border-radius:10px;border-width:1px" >
 <span class="kt-btn-inner-text">Accede A-ho-ra al Método <strong><em>G-e-n-g-h-i-s K-h-a-n</em></strong></span>
   </a>
  </div>
</div>


This Question was asked in StackOverflow by Lenin Zapata and Answered by Carsten Massmann It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?