Removing a link in jQuery

I have a bit of html for example:

<a href="#somthing" id="a1"><img src="something" /></a>
<a href="#somthing" id="a2"><img src="something" /></a>

I need to remove links, so I just left a couple of image tags. What would be the most efficient way to do this with jQuery?

+5
source share
3 answers
$("a > img").parent()   // match all <a><img></a>, select <a> parents
   .each( function()    // for each link
   { 
      $(this).replaceWith(              // replace the <a>
         $(this).children().remove() ); // with its detached children.
   });
+8
source

This should do it:

$('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); });
+4
source

In plain javascript, it will be something like:

<script type="text/javascript">
window.onload = function(){
  var l = document.getElementsByTagName("a");
  for(i=0, im=l.length; im>i; i++){
    if(l[i].firstChild.tagName == "img"){
      l[i].parentNode.replaceChild(l[i].firstChild,l[i]);
    }
  }
}
</script>
+1
source

All Articles