defrex
defrex

Reputation: 16445

Stripping out a link in jQuery

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?

Upvotes: 6

Views: 1200

Answers (3)

roenving
roenving

Reputation: 2646

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>

Upvotes: 1

Andrew Moore
Andrew Moore

Reputation: 95444

This should do it:

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

Upvotes: 4

Shog9
Shog9

Reputation: 159698

$("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.
   });

Upvotes: 9

Related Questions