views:

229

answers:

3

I have a bit of html like so:

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

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

+6  A: 
$("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.
   });
Shog9
If there are any siblings to the image then this will copy them as well. You may want to use $(this).children("img").remove() instead.
Sugendran
@Sugendran: true.
Shog9
There don't happen to be any siblings. But that is a good point.
defrex
+2  A: 

This should do it:

$('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); });
Andrew Moore
A: 

Ain''t got any idea of how a jQuery code would be, but in plain javascript it would 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>
roenving
jQuery is being used today to elegantly replace peaces of code like your propose here. Thanks anyway!
Alexander Prokofyev
Seriously, this snippet just shows the elegance of jQuery. This code and the code by Shog9 are exactly the same but, one is smaller and so much neater to read.Though, this code will perfectly do the job too!
Adhip Gupta
Elegantly -- yes it looks rather neat, but inside jQuery it's much larger, so if you ain't got other reasons to engage a huge library, use this. But of course, defrex asked for a jQuery-thing and this isn't !-)
roenving
Perhaps this is bad of me, but I've gotten so used to jquery (and libraries like it) that I can't even imagine trying to code in raw js again. I think my users can handle the overhead.
defrex