Alexandros Alexandros - 5 months ago 9
Javascript Question

Clear text but keep image inside <a> hyperlinks using 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

Answer

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;
    }
});
Comments