Clear text but save image inside <a> hyperlinks with jQuery

How can I remove Product X and save images using jquery only?

<span class="product-field-display"> <a href="/products/product-a-detail" original-title="Product A"> <img alt="product-a" src="/images/resized/product_a_180x180.png">Product A</a> </span> <span class="product-field-display"> <a href="/products/product-b-detail" original-title="Product B"> <img alt="product-b" src="/images/resized/product_b_180x180.png">Product B</a> </span> 

I tried:

 $j('span.product-field-display a').html(''); 

and with:

 $j('span.product-field-display a').text(''); 

but it is cleared, not just text

+4
source share
4 answers

You can capture the image, clear the anchor and return the image:

 $j('#gkComponent .productdetails-view .product-related-products .product-field-type-R span.product-field-display a').each(function() { var $this = $(this); var img = $this.find('img').detach(); $this.empty().append(img); }); 

Or do this by removing all text nodes from the anchor via the DOM, leaving the img element intact:

 $j('#gkComponent .productdetails-view .product-related-products .product-field-type-R span.product-field-display a').each(function() { var node, nextNode; node = this.firstChild; while (node) { nextNode = node.nextSibling; if (node.nodeType === 3) { // 3 = text node node.parentNode.removeChild(node); } node = nextNode; } }); 
+4
source

You can try this

 $('.product-field-display a').filter(function(){ return $(this).html($(this).find('img')); }); 

Demo.

+1
source

Since jQuery does not work well with text nodes, one way is to process it in pure JS:

 $('span.product-field-display a').each(function() { var nodes = this.childNodes; for (var i = nodes.length - 1; i >= 0; --i) { if (nodes[i].nodeType == 3) { this.removeChild(nodes[i]); } } }); 
+1
source

try it worked for me

 $('#AddToWishList').click(function(e) { e.preventDefault(); var dt ='Product_ID=1'; var $this = $(this); var img = new Image(); img.src="images/progress.gif"; $this.empty().append(img); $.post('ajax/add_wish.php', dt, function(data) { $this.empty().append('<i class="fa fa-star"></i>Wishlist'); $this.attr('class','btn btn-block btn-primary'); $this.attr('disabled','disabled'); }); }); 
 <a class="btn btn-block btn-default" href="JavaScript:;;" id="AddToWishList"><i class="fa fa-star"></i>Wishlist</a> 
+1
source

Source: https://habr.com/ru/post/1479158/


All Articles