开发者

Use jquery to find the first child node with text

I need to select the first bit of readable text of an element.

<li>
Hello world
</li>

and

<li>Hello world</li>

should read 'Hello world'

<li&g开发者_高级运维t;
<span>Hello Jupiter</span>
What's up?
</li>

should read 'Hello Jupiter'

I am having trouble with the whitespaces, so

function getTextFromFirstChild(el) {
    return $(el).contents().first().text();
}

will return a lf but nothing else (it is the first text node after all)


function getTextFromFirstChild(el) {
    return $(el).contents(":not(:empty)").first().text();
}

seems to do the trick


Try:

.contents().first().text()


I'd do this:

function getTextFromFirstChild(el) {
    var result;
    $(el).contents().each(function() {
        if( result = $.trim( $(this).text() ) ) {
            return false;
        }
    });
    return result;
}

Loop over the contents, trimming the white space from the text content. If the trimmed content gives a truthy result, it will trigger return false; breaking the loop, and returning the result.


I would think the best way to accomplish this is with recursion:

function getTextFromFirstChild(el) {
    var ch = $(el).children();
    if (ch.length < 1) return $(el).text();
    alert($(el).html());
    return getTextFromFirstChild(ch[0]);
}


I would do this:

$("selector").contents().filter(function() {
    return (this.innerText) ? this.innerText.match(/\S/) : false;
}).first();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜