Home > Enterprise >  Replace only text within multiple divs using jquery
Replace only text within multiple divs using jquery

Time:09-19

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 >
  <div >
   <a  href="#" style="border-radius:10px;border-width:1px" >
     <span >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

CodePudding user response:

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 >
  <div >
   <a  href="#" style="border-radius:10px;border-width:1px" >
 <span >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>

CodePudding user response:

You could try below code, it is working for the provided HTML content.

$(document).ready(function () {
  var HTMLContent = $('.reemplazo-guion').html().replace(/-/g, '');
  $('.reemplazo-guion').html(HTMLContent)
});
  • Related