Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only tag using jQuery?

I want to remove the span using jQuery, I have tried the .unwrap(); but it's not working.

<div>
<ul>
<li><a href="#"><span>link</span></a></li>
<li><a href="#"><span>link</span></a></li>
</ul>
</div>
like image 658
Wasim Shaikh Avatar asked Apr 27 '10 06:04

Wasim Shaikh


People also ask

How do I remove a specific tag in HTML?

For HTML tags, you can press Alt+Enter and select Remove tag instead of removing an opening tag and then a closing tag.

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

How do you remove an element?

Removing an element using the removeChild() method First, select the target element that you want to remove using DOM methods such as querySelector() . Then, select the parent element of the target element and use the removeChild() method.

Why remove function is not working in jQuery?

You need to either move the function outside the ready handler (making it global), or, better, bind the click with jQuery: $(document). ready(function(){ $(this). mousedown(function(e){ var $x = e.


2 Answers

Obviously, unwrap doesn't work as the spans only have text nodes inside them and jquery doesn't handle text nodes too well... this works however (you could use also jQuery.text instead of jQuery.html if you're sure that the span only contains text):

$('li a span').replaceWith($('li a span').html());

Working example

Edit: Actually, it seems that unwrap works as well if you use jQuery.contents to work around the jquery's inability to directly select text nodes:

$('li a span').contents().unwrap();
like image 155
kkyy Avatar answered Oct 16 '22 18:10

kkyy


$('li').find('span').remove();

or

$('li').find('span').detach();

If you want to remove the wrapping only, try

var buffer = $('li').find('span').text();
$('li').find('span').parent().html(buffer);
like image 23
jAndy Avatar answered Oct 16 '22 18:10

jAndy