[英]Delete text between two tags with jQuery
Hello there fellow developers, I am trying to delete a certain character between two tags using 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 €</span>
</div>
In this case the "x" between the strong and the span tag. 在这种情况下,强标记和span标记之间的“x”。 I can't search for "x" in the product-details class because there could be an "x" in the name of the product.
我无法在product-details类中搜索“x”,因为产品名称中可能有“x”。 Thats why I thought it would be the best thing to say that everything between the
<strong>
and <span>
should be deleted. 这就是为什么我认为应该删除
<strong>
和<span>
之间的所有内容是最好的事情。
Also this must be done using jQuery, I have no access to this code to delete it myself. 这也必须使用jQuery完成,我无法访问此代码以自行删除它。 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. 给出示例,您可以从
.product-details
div中删除所有子textNodes。 You can do that in jQuery by using contents()
, filter()
then remove()
: 您可以使用
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 €</span> </div>
Alternatively, You can get target the node element using DOM relationship. 或者,您可以使用DOM关系来定位节点元素。 Here in example, You can get a reference to
<strong>
node then get desired element using nextSibling
在示例中,您可以获得对
<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 €</span> </div>
Use $('.product-details').children()
to get the elements with the tag. 使用
$('.product-details').children()
来获取带有标记的元素。 Since, x
do not have any tag this will be removed. 由于,
x
没有任何标签,因此将被删除。 Then, set this result as the new html content of .product-details
. 然后,将此结果设置为
.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 €</span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.