Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove wrapping <a> anchor tag from an image using jQuery

I am trying to remove the first wrapping tag of an image IF one exists

   <div class="feature">
        <a>
          <img width="252" height="79" alt="" src="http://localhost:81/site/wp-
          content/uploads/2011/12/home-highlights.jpg" title="home-highlights" 
          class="alignnone size-full wp-image-55">
        </a>
   </div>

I've had a look at a number of options and I assume my approach is correct here:

$(".feature img").closest('a').remove();

If I use the example above,it removes the image too which is not what I want of course.

like image 354
SixfootJames Avatar asked Feb 15 '12 14:02

SixfootJames


People also ask

How do you remove an anchor tag?

To disable a HTML anchor element with CSS, we can apply the pointer-events: none style. pointer-events: none will disable all click events on the anchor element. This is a great option when you only have access to class or style attributes. It can even be used to disable all the HTML links on a page.

How to remove tag div jQuery?

To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.

What is remove in jQuery?

jQuery remove() Method The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.


2 Answers

jQuery has a built-in function for it: unwrap:

$(".feature a > img").unwrap();

unwrap docs:

Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

child(>) selector docs:

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

Thanks @am not i am!
JSFiddle DEMO

like image 159
gdoron is supporting Monica Avatar answered Oct 28 '22 23:10

gdoron is supporting Monica


The unwrap method is the one you want:

 $(".feature a").children('img').unwrap();
like image 28
Rich O'Kelly Avatar answered Oct 29 '22 01:10

Rich O'Kelly