tags:

views:

70

answers:

2

I'd like to keep the first <a> and the <span>, but remove the rest in the following:

<div>
    <a href="http://aerospace.com"&gt;Aerospace&lt;/a&gt; and 
    <a href="http://aviation.com"&gt;Aviation&lt;/a&gt;
    <span class="blah">(15)</span>
</div>

What I'm finding is that there doesn't seem to be an obvious of matching the plain text and . I'm trying to use nextAll() with a filter:

$("a:contains('Aerospace')").each(function() {
    $(this).nextAll().filter(":not(span)").empty();
});

But the and text is left there.

Is it possible to match text in jQuery? Is there such a thing as a text selector so I could use something like filter (":isText()")?

A: 
$("a:contains('Aerospace')").parent().contents().each(function() {
    if ( this.nodeType == 3 ) {
        var text = this.textContent? this.textContent: this.innerText;
        text = $.trim( text );
        if ( text.length ) {
            alert( text );
        }
    }
});

Off the top of my head something like this should work, you descend upwards to the parent and operate on all the contents, not just element nodes which have a nodeType of 1 but including textNodes which have a nodeType of 3.

Let me know if that doesn't work.

meder
updated with textContent/innerText example.
meder
Is `innerText` supposed to be `nodeValue`? I'm testing against IE8/FF 3.5 and innerText is always undefined but nodeValue seems to work. Also, how would you delete the text instead of displaying the alert box?
Alex Angas
Did you try my latest version from half or so hour ago? innerText is for IE, textContent is for modern DOM parsers. It should use the modern and fallback to innerText.
meder
You could try resetting the nodeValue/innerText/textContent to blank to remove it.
meder
why not use `var text = $(this).text()` ? jQuery makes things browser compatible.
Eric
A: 

How about copying the span, then removing everything from the div, then putting the span back in?

$("a:contains('Aerospace')").each(function()
{
    var span = $(this).parent().children("span").clone();
    $(this).parent().empty().append(span);
});
Eric