簡體   English   中英

使用jQuery刪除兩個標記之間的文本

[英]Delete text between two tags with jQuery

你好開發人員,我試圖使用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>

在這種情況下,強標記和span標記之間的“x”。 我無法在product-details類中搜索“x”,因為產品名稱中可能有“x”。 這就是為什么我認為應該刪除<strong><span>之間的所有內容是最好的事情。

這也必須使用jQuery完成,我無法訪問此代碼以自行刪除它。 希望任何人都有解決方案,因為到目前為止我沒有任何工作。

給出示例,您可以從.product-details div中刪除所有子textNodes。 您可以使用contents()filter()然后remove()在jQuery中執行此操作:

 $('.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> 

或者,您可以使用DOM關系來定位節點元素。 在示例中,您可以獲得對<strong>節點的引用,然后使用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> 

使用$('.product-details').children()來獲取帶有標記的元素。 由於, x沒有任何標簽,因此將被刪除。 然后,將此結果設置為.product-details的新html內容。

 $('.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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM