How to convert tag has image URL in href to tag using jquery?

I have HTML contain multiple <a> tag that has image URL in href attribute. I want to convert that <a> to <img> tag and href attribute convert to src and text of anchor set in alt attribute of the image as shown in the bottom.

<a href="">jpg image</a>
<a href="">png image</a>
<a href="">stackoverflow</a>

Should convert to

<img src="" alt="jpg image" />
<img src="" alt="png image" />
<a href="">stackoverflow</a>

How can I do this work?

0

3 Answers

You should iterate each tag.

$('a').each(function(i, a) { var src, txt; src = $(a).attr('src'); txt = $(a).text(); // or .html() // now lets replace the <a> with <img> $(a).replaceWith('<img src="' + src + '" alt="' + txt + '">');
});

hope that this will help you

0

Use a matching attribute selector.

[attr$=value]

Represents an element with an attribute name of attr and whose last value is suffixed by "value".


(function() { var anchors = $("[href$='.jpg'], [href$='.png']"), i = 0, len = anchors.length; for (i, len; i < len; i++) { var anchor = $(anchors[i]), href = anchor.attr('href'), text = anchor.text(), img = $("<img/>", { src: href, alt: text }); anchor.replaceWith(img); }
})();
<script src=""></script>
<a href="">jpg image</a>
<a href="">png image</a>
<a href="">stackoverflow</a>

You can select anchor tag contain image URL using jQuery Attribute Ends With Selector [name$=”value”].

$("a[href$='.jpg'], a[href$='.JPEG'], a[href$='.png'], a[href$='.gif']").someFunction();

Or using regex in .filter()

$("a").filter(function(){ return this.href.match(/.(jpg|JPEG|png|gif)$/);
}).someFunction();

Then you need to convert selected tag to new tag using .replaceWith()

selectedAnchor.replaceWith(function(){ return '<img src="'+ this.href +'" alt="'+ this.textContent +'" />';
});
$("a").filter(function(){ return this.href.match(/.(jpg|JPEG|png|gif)$/);
}).replaceWith(function(){ return '<img src="'+ this.href +'" alt="'+ this.textContent +'" />';
});
<script src=""></script>
<a href="">png image</a>
<a href="">stackoverflow</a>
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like