How to convert tag has image URL in href to
tag using jquery?
Sebastian Wright
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?
03 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
0Use 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