0

I asked a somewhat similar question this afternoon and then realized as great as the answer is my question was not correct...

given the following:

<p class="p"> 
<div> </div> 
<div>
<a href="foo"> a </a>  &gt;
<a href="foo1"> b </a> 
<a href="foo2"> c</a> 
<a href="foo3"> b </a>  &gt;
<a href="foo4"> c </a> 
</div>
</p>

I need to remove the "&gt"` from the page as well as the a tag that precedes it. This is a dynamic list so it will continously grow over time. I need to someone latch onto the ">" remove it and then remove the a tag before it.

Any suggestions?

Martin Brody
  • 233
  • 1
  • 6
  • 12

1 Answers1

2

Your markup is invalid. The <div> elements are going to be kicked out of the <p>.

After correcting your markup, you could do this:

var els = $('.p');

do {
    els.contents().each(function(i,el) {
        if( el.nodeType === 3 && $.trim( el.data ) === '>' ) {
            el.parentNode.removeChild(el.previousSibling);
            el.parentNode.removeChild(el);
        }
    });
} while( ( els = els.children() ).length )

JSFIDDLE DEMO


Or with a little more jQuery:

var els = $('.p');

do {
    els.contents().each(function(i,el) {
        if( el.nodeType === 3 && $.trim( el.data ) === '>' ) {
            $(el.previousSibling).remove();
            $(el).remove();
        }
    });
} while( ( els = els.children() ).length )

JSFIDDLE DEMO


Or this:

var els = $('.p');

do {
    els.contents().each(function(i,el) {
        if( el.nodeType === 3 && $.trim( el.data ) === '>' ) {
            $(el.previousSibling).add(el).remove();
        }
    });
} while( ( els = els.children() ).length )

JSFIDDLE DEMO

RightSaidFred
  • 11,209
  • 35
  • 35