Boel
Boel

Reputation: 976

how to get the text of an anchor that is inside a text node in jQuery

I'm doing something like this to retrieve the text content from the child nodes of a class:

$(data).find(".mw-content-ltr").contents().each(function(_, row) {
    // ...
    } else if ( row.nodeType === 3 && $.trim(row.nodeValue).length ) {
       var textNodeValue = $.trim(row.nodeValue);
       console.log(textNodeValue);
    }
});

The problem is that if the text node has some anchors inside, like this:

When<a href="/wiki/Raquel_Ochmonek" title="Raquel Ochmonek"> Raquel Ochmonek</a> comes over to sit 
for <a href="/wiki/Brian_Tanner" title="Brian Tanner">Brian</a>, 
a burglar breaks into the house through the master bedroom 
where <a href="/wiki/ALF" title="ALF">ALF</a> is hiding. 

my code won't retrieve them, resulting in something like this:

When

comes over to sit for

, a burglar breaks into the house through the master bedroom where

is hiding. 

when I need something like this:

When  Raquel Ochmonek  comes over to sit for Brian, a burglar breaks into the house through the master bedroom where is hiding. 

Thanks in advance!

Upvotes: 0

Views: 269

Answers (1)

Kyle Muir
Kyle Muir

Reputation: 3925

Try this:

$(".mw-content-ltr").text()

Fiddle comparing the two: http://jsfiddle.net/KyleMuir/GeRVV/2/

EDIT: since there is other data inside the class that you aren't interested in, would something like this work?

$(".mw-content-ltr").contents().each(function (_, row) {
    if (row.nodeType === 3 && $.trim(row.nodeValue).length) {
        var textNodeValue = $.trim(row.nodeValue);
        console.log(textNodeValue);
    } else if (row.nodeType == 1) {
        var nodeValue = $.trim($(row).text());
        console.log(nodeValue);
    }
});

JSFiddle: http://jsfiddle.net/KyleMuir/GeRVV/5/

Upvotes: 3

Related Questions