swood
swood

Reputation: 55

Jquery to find the last nested element

I understand the use of using .last() or :last-child etc. to get the last sibling of an element, but how would one get the most inner elements text() with the same tag name without using any classes or ids?

For example:

$(body).find('div').text();
<div>
    <div>
        <div>
            <div>Get this text</div>
        </div>
    </div>
    <div>
        <div>
            <div>
                <div>
                    <div>And get this text</div>
                </div>
            </div>
       </div>
    </div>
</div>

When I have used a loop to return the text on each div using $.each, I am returning duplications of text for each div's text().

Thanks in advance

Upvotes: 2

Views: 1947

Answers (2)

rby
rby

Reputation: 786

This is an inherently recursive problem and the following does the job too:

function getText(elem) {
    if (elem.children().length === 0) {
        console.log( elem.html() );
    } else {
        elem.children().each( function() {
                getText($(this));
            }
        );
    }
}

getText( $('div').first() );

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240868

You could select div elements that don't contain a child element by combining the :not()/:has() selectors. This essentially negates all div elements that have a child:

$('div:not(:has(*))').text();

If you want an array text strings:

Example Here

var textArray = $('div:not(:has(*))').map(function (_, el) {
    return el.innerText;
}).get();

console.log(textArray);

Upvotes: 3

Related Questions