Plain text selector in jQuery

I would like to keep the first <a>

and <span>

but remove the rest in the following:

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

      

What I find is that there seems to be no obvious match for plain text and

. I am trying to use nextAll () with a filter:

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

      

But the text and

stays there.

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

?

+2


source to share


2 answers


$("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 );
        }
    }
});

      

At the top of my head, something like this should work, you go down to the parent object and work with all content, not just tags element

that have nodeType

from 1

, but contain text nodes that have nodeType

of 3

.



Let me know if this doesn't work.

+2


source


How do I copy span

and then delete everything from div

and then return span

?



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

      

0


source







All Articles