Reputation: 9293
I have some unwanted tags inside contenteditable divs and need to remove them.
Those are
and span
Tried with jquery unwrap
function but but the result is undefined
because it removes parent's tags and not the tags itself.
Any help? In the example below the expected console is:
lorem ipsum lorem ipsum lorem ipsum
$('button').on('click', function(){
$('span').unwrap();
console.log($('#story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='story' id='story'>
loem ipsum <span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>
Upvotes: 2
Views: 62
Reputation: 115272
You need to unwrap the text nodes, so use contents()
method to get all child nodes. And replace
using String#replace
method where html()
method with a callback(the second argument in the callback is old HTML content) can be used for updating the content.
$('button').on('click', function() {
// get span tags child nodes and unwrap
$('#story span').contents().unwrap();
// remove from html content
$('#story').html((_, html) => html.replace(/ /g, ''))
console.log($('#story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='story' id='story'>
loem ipsum <span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>
Upvotes: 1
Reputation: 6755
you have to use like
$("#story").find("span").contents().unwrap();
$('button').on('click', function(){
$("#story").find("span").contents().unwrap();
console.log($('#story').html().replace(/ /g, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='story' id='story'>
loem ipsum <span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>
Upvotes: 1
Reputation: 36594
You can change outerHTML
to innerHTML
for <span>
and use replace to remove
$('button').on('click', function(){
$('span').each(function(){
this.outerHTML = this.innerHTML;
})
let html = $('#story').html();
$('#story').html(html.replace(/ /g,""))
console.log($('#story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='story' id='story'>
loem ipsum <span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>
Upvotes: 1