简体   繁体   中英

Is there a better way to write descendant Selector?

I am new to JS and I want to dynamically delete one of the links on the footer based on some condition. But with my footer nested under multiple class the code to remove the link is:

 $( ".footer .footer__container .footer__information .footer__links .footer__link").last().empty();

is there any better way to write this particular line having multiple classes nested? Just a note: In my original project file, ".footer" class is what exposed to my file. So my top level class has to start with ".footer".

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Delete link in a footer demo</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>
    Hello, <span>Person</span> <em>and person</em>.
</p>

<!-- footer has 3 links of which last link needs to be deleted on button press -->
<footer role="footer" class="footer">
    <div class="footer__container">
        <div class="footer__logo">
            <img src="images.png" alt="Images">
        </div>
        <div class="footer__information">
            <div class="footer__links">
                <a target="_blank" href="https://link1" aria-label="link1" class="footer__link">link1</a>
                <a target="_blank" href="https://link2" aria-label="link2" class="footer__link">link2</a>
                <a target="_blank" href="https://link3" aria-label="link3" class="footer__link">link3</a>
            </div>
        </div>
    </div>
</footer>
<button>Call empty() on above paragraph</button>

<script>
    $( "button" ).click(function() {
        $( ".footer .footer__container .footer__information .footer__links .footer__link").last().remove();
    });
</script>

</body>
</html>

Unless you have another section of HTML with similar internal classes, you do not need to be that specific. All you should need in this case is

$(".footer_link").last().remove(); // or .empty(), whichever you intended

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