Get only visible text with jquery

前端 未结 3 1894
死守一世寂寞
死守一世寂寞 2021-01-13 16:53

Lets say I have some html like this:

FoohiddenBar

In

3条回答
  •  萌比男神i
    2021-01-13 17:36

    The trick is to modify the DOM in place to get the text, and then revert it back to the original when we're done with it. The following does the trick:

    function get_visible_text(content) {
        // Not so easy to get the visible text
        var saved = $(content).clone();
        // Remove the hidden parts
        $(content).find(':hidden').remove();
        // Get the remaining text
        var visible_text = $(content).text();
        // Now revert back to our saved version
        $(content).replaceWith(saved);
        return visible_text;
    }
    

    Note that @slindberg is correct, @adeneo's answer will not work because cloned objects are invisible until they are inserted into the DOM. By modifying the DOM in place, we avoid that problem.

提交回复
热议问题