JQuery remove tag in custom element

I have the following markup generated dynamically with split and join function

<span>
    <em style="position: relative;">T</em>
    <em class="good" style="position: relative;">H</em>
    <em style="position: relative;">E</em>
    <em style="position: relative;">S</em>
</span>

I want to remove the em tag for elements that do not have a good class. Get something like this:

<span>
    T <em class="good" style="position: relative;">H</em> ES
</span>

I realized that I can use the spread for this, but it does not work:

$(document).ready(function(){
$("#njoin").live('click', function(){
$('em').each(function() {
    if ($(this).hasClass('good')) {
         $('.good').unwrap();
    }
});         
});
});

What should I do to make it work? thank you

+3
source share
5 answers
$('em').each(function(){
if(!$(this).hasClass('good'))
   $(this).remove();
});

It should be so simple.

+3
source

It:

$('em:not(.good)').replaceWith(function(){
    return document.createTextNode($(this).text());
});

If you need to prevent spaces between any resulting elements, do not put spaces between them in the source HTML.

+1
source

$('#njoin').click(function() {
    $('em').each(function() {
        if($(this:not).hasClass('good')) {
            $('.good').remove();
        }
    });
});
0

jQuery 1.4 unwrap() ( ) - ?:

$('em:not(".good")')
  .each(function() { this.innerHTML = '<span>' + this.innerHTML + '</span>'; })
  .find('span').each(function() { $(this).unwrap(); });

:

<span><span>T</span> <em class="good" style="position: relative;">H</em> <span>E</span><span>S</span></span>
0

, , html , , :

$("#njoin").live('click', function(){
    $('em').each(function(){ 
        if(!$(this).hasClass('good')) 
        {
            this.outerHTML = $(this).html();
        }
    });
});

Edit: Working example

0
source

Source: https://habr.com/ru/post/1732384/


All Articles