首页 > 解决方案 > 错误选择包含类的 div

问题描述

  1. 查找包含具有特定类的“a”元素的 div(此步骤已成功)
  2. 对于那个特定的 div(包含具有特定类的“a”元素),应该找到另一个类,将为其删除一个类。此步骤失败,因为所有包含类 filter-options-title 的 div 都将丢失“已关闭”类。

    <script>
        require(["jquery"], function ($) {
                if ($("div.filter-optie").find('.shopby_link_selected')) {
                    $("div.filter-optie").find('.filter-options-title').removeClass('closed'); //this should only happen when the 'a' element with class shopby_link_selected has been found, which is not happening right now with this piece of code.
                }
        });
    </script>
    

有什么想法我可以实施以使其更强大,并使其实现我想要的吗?

附上HTML:

<div class="filter-optie">
    <dt role="heading" aria-level="3" class="filter-options-title closed">
        <label class="active" for="layered-filter-merk">BRAND</label>
    </dt>
    <dd class="filter-options-content">
        <ol class="items shopby_filter_items_attr_merk">
            <form data-shopby-filter="attr_merk" data-shopby-filter-request-var="merk">
            <li class="item" data-label="LABEL">
                <a class="shopby_filter_item_5cd9ce0ea7fbd shopby_link_selected" href="">
                <input name="shopby[brand][]" value="3989" type="radio" style="" checked="">
                <span class="label">XXXX</span>
                <span class="count">4<span class="filter-count-label">PRODUCTS</span></span>
                </a>
            </li>
            </form>
        </ol>
    </dd>
</div>

标签: javascriptfind

解决方案


@DigitalJedi,几乎是正确的,因为这.closed将从所有有 a 的地方删除该类,.shopby_link_selected但我相信根据您的 html,DOM 遍历是不正确的。

$("div.filter-optie .shopby_link_selected").each(function() {
  $(this).closest('.filter-optie).find('.filter-options-title').removeClass('closed');
});

这将找到所有带有 class 的锚标记.shopby_link_selected,然后对于它们中的每一个,它将在 DOM 中搜索父级.filter-optie,然后在 DOM 中搜索.filter-options-title并删除.closed该类。


推荐阅读