简体   繁体   中英

Delete text between two tags with jQuery

Hello there fellow developers, I am trying to delete a certain character between two tags using jQuery:

<div class="product-details">
  <p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p>
  <strong>1</strong> x
  <span class="price">9,14&nbsp;€</span>
</div>

In this case the "x" between the strong and the span tag. I can't search for "x" in the product-details class because there could be an "x" in the name of the product. Thats why I thought it would be the best thing to say that everything between the <strong> and <span> should be deleted.

Also this must be done using jQuery, I have no access to this code to delete it myself. Hope anybody has a solution for me since nothing worked for me so far.

Given the example you can simply remove all child textNodes from the .product-details div. You can do that in jQuery by using contents() , filter() then remove() :

 $('.product-details').contents().filter(function() { return this.nodeType == 3 && this.nodeValue.trim(); }).remove(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="product-details"> <p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p> <strong>1</strong> x <span class="price">9,14&nbsp;€</span> </div> 

Alternatively, You can get target the node element using DOM relationship. Here in example, You can get a reference to <strong> node then get desired element using nextSibling

 var element = document.querySelector('.product-details > strong'); //element.nextSibling.nodeValue = "Modified Value"; element.nextSibling.parentNode.removeChild(element.nextSibling) 
 <div class="product-details"> <p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p> <strong>1</strong> x <span class="price">9,14&nbsp;€</span> </div> 

Use $('.product-details').children() to get the elements with the tag. Since, x do not have any tag this will be removed. Then, set this result as the new html content of .product-details .

 $('.product-details').html($('.product-details').children()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="product-details"> <p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p> <strong>1</strong> x <span class="price">9,14&nbsp;€</span> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM