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?
From stackoverflow
-
$("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. });Sugendran : 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.Shog9 : @Sugendran: true.defrex : There don't happen to be any siblings. But that is a good point. -
This should do it:
$('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); }); -
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>Alexander Prokofyev : jQuery is being used today to elegantly replace peaces of code like your propose here. Thanks anyway!Adhip Gupta : 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!roenving : 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 !-)defrex : 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.
0 comments:
Post a Comment