简体   繁体   中英

Can't reach element by using a combination of .parent() and .next() methods

I'm binding the following function to a toggle button I have created to hide/unhide content that is located bellow the button, but on an other level in the DOM.

var togglelabel = packagehead.append("<div>").children().last().addClass("togglewrap").append("<label>")
        .children().last().addClass("toggle android header-toggle")
        .on('click', function(){
            $(this).parent().parent().next('.hidable').toggle();
        });

The html structure looks like this:

<div>
    <div class="packageheader">
        <span>Package #1501</span>
        <div class="togglewrap">
            <label class="toggle android header-toggle">
                <input type="checkbox">
                <p>
                    <span>More</span>
                    <span>Less</span>
                </p>
                <a class="slide-button">
                </a>
            </label>
        </div>
    </div>
    <br>
    <p class="hidable">
        <pre>content here</pre>
    </p>
</div>

This code doesn't work to hide the <p> with the class .hidable . I've tried 'debugging' the code using console.log() to see what element 'this' represents and found that it does, as expected, represent the label element.

So I thought that using the following chain:

$(this).parent().parent().next('.hidable').toggle();

Would correctly go 2 levels up to the <div class="packageheader"> and then take the next sibling with the class hidable, which would be <p class="hidable">

Here is a screenshot of the structure, to be sure I didn't miss anything: 在此输入图像描述

You can do this :

$(this).closest('.packageheader').nextAll('.hidable').first().toggle();

Note that it's slightly preferable to use closest instead of parent().parent() as it won't break as easily when the HTML changes and it's easier for the maintainer to decipher what the code does.

Note also that your HTML is invalid, you can't have a PRE inside a P .

Demonstration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM