在不影响子元素的情况下插入元素(限制jQuery的选择器的深度)



让我们假设我有以下 DOM 结构:

<li role="treeitem" aria-selected="false" aria-level="2" aria-labelledby="3_anchor" aria-expanded="true" id="3" class="jstree-node  jstree-open">
    <div unselectable="on" role="presentation" class="jstree-wholerow">&nbsp;</div>
    <i class="jstree-icon jstree-ocl" role="presentation"></i>
    <a class="jstree-anchor" href="#" tabindex="-1" id="3_anchor">
        <i class="jstree-icon jstree-themeicon" role="presentation"></i>Hombre (3)
    </a>
    <ul role="group" class="jstree-children">
        <li role="treeitem" aria-selected="false" aria-level="3" aria-labelledby="10_anchor" id="10" class="jstree-node  jstree-leaf">
            <div unselectable="on" role="presentation" class="jstree-wholerow">&nbsp;</div>
            <i class="jstree-icon jstree-ocl" role="presentation"></i>
            <a class="jstree-anchor" href="#" tabindex="-1" id="10_anchor">
                <i class="jstree-icon jstree-themeicon" role="presentation"></i>Corbatas (10)
            </a>
        </li>
        <li role="treeitem" aria-selected="false" aria-level="3" aria-labelledby="9_anchor" id="9" class="jstree-node  jstree-leaf jstree-last">
            <div unselectable="on" role="presentation" class="jstree-wholerow">&nbsp;</div>
            <i class="jstree-icon jstree-ocl" role="presentation"></i>
            <a class="jstree-anchor" href="#" tabindex="-1" id="9_anchor">
                <i class="jstree-icon jstree-themeicon" role="presentation"></i>Sudaderas (9)
            </a>
        </li>
    </ul>
</li>

现在假设我想在最上li项的 a 元素(即带有文本Hombre (3)a)之后插入一些内容。

如果我使用

$("<i>").insertAfter('a', my_dom_element);

i元素将插入到每个a元素(总共 3 个)中,这就是我想要防止的。

如何强制 jQuery 在 DOM 中仅向下搜索 1 级,而不是遍历所有元素?

我不能使用任何类来限制搜索,因为我不知道 DOM 会有什么类。我正在寻找限制jQuery的DOM扫描级别

编辑:

我几乎正在寻找这个:http://bugs.jquery.com/ticket/9391

您可以使用属性 aria-level 将值为 2 的 li 定位。 然后使用直接子选择器仅定位直接锚元素:

$("<i>").insertAfter('li[aria-level="2"] > a', my_dom_element);

更新:不使用类,ID,属性等。

$("<i>").insertAfter('a:first', my_dom_element);

$("<i>").insertAfter('a:eq(0)', my_dom_element);

这个怎么样:

$( "<i>" ).insertAfter( "a:first" , my_dom_element);

更新:

对于两个 a 标签,我认为您可以这样做:

$("<i>").insertAfter('a:eq(0),a:gt(0)', my_dom_element);

最新更新