Search code examples
javascriptjqueryparent

Get the text in a grandparent element


I'm trying to modify this function to get the text from the grandparent element

span.html(checked.map(function () { return $(this).parent().text(); }).get().join());

Both of these functions are returning the grandparent text as well as the text in it's sibling element (<div class=CheckMark>). How can I modify it to only return the text from the grandparent element?

span.html(checked.map(function () { return $(this).parent().parent().text(); }).get().join());

span.html(checked.map(function () { return $(this).parents(':eq(1)').text(); }).get().join());

HTML

<li><a href="#">
    <label onclick="toggle_colorbox_alt(this.children[0]);">
        <div style="background-color: #000000" class="color">
            <div class=CheckMark>&#10003;</div>
            <input type="checkbox" name="color[]" value="value" class="cbx"/>
        </div>
        Text I Want
    </label>
</a></li>

Solution

  • You seem to want to get the text of the label excluding its children.

    You can do this :

    var p = $(this).closest('label').clone();
    p.children().remove();
    var txt = p.text();
    

    Or in a shorter chained way :

    var txt = $(this).closest('label').clone().children().remove().end().text();
    

    Demonstration