Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear text but keep image inside <a> hyperlinks using jQuery

Tags:

jquery

How i can remove "Product X" and only keep the images using jquery?

<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 with:

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

and with:

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

but it gets all cleared and not only the text

like image 232
Alex Bogias Avatar asked Mar 24 '23 02:03

Alex Bogias


1 Answers

You can grab the image, clear out the anchor, and put the image back:

$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 it 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;
    }
});
like image 163
T.J. Crowder Avatar answered Apr 05 '23 12:04

T.J. Crowder