首页 > 解决方案 > 找到匹配文本后单击特定兄弟

问题描述

我有许多下面的 ' k-top' div 元素,具有相同的内部 div 结构,除了在两个地方不同的唯一文本,在 'k-in' 和我的复选框 id 中。

<div class="k-top">
<span class="k-icon k-i-expand"></span><-------------- trigger click on this if below text is found
<span class="k-checkbox-wrapper" role="presentation">
<input type="checkbox" tabindex="-1" id="unique TEXT99" class="k-checkbox">
<span class="k-checkbox-label checkbox-span"></span>
</span>
<span class="k-in">unique TEXT99</span></div><- if this text is found in k-in trigger click on elem above

我想遍历我的所有span.k-ins内容,直到找到匹配包含'唯一'的 innerText ,然后一旦找到唯一的,我想.click();在它的兄弟元素' .k-i-expand'上,如上面的标记所示。我不想触发.click(); 在所有.k-i-expand与我的 ' ' 所在位置具有相同父级的特定一个上unique text

到目前为止,我已经尝试过.closest,我也尝试过兄弟.parent.. 都返回 null 或 undefined.. 注意,我没有使用 jQuery。

以下内容可以成功单击全部.k-i-expand- 但我只需要 .click() k-ininnerText包含“唯一”的那个。理想情况下,我会使用开头或包含,但如果需要,我会指定整个单词,即unique TEXT99

      let exp = document.querySelectorAll('.k-i-expand'); 
        let i;
        for (i = 0; i < exp.length; ++i) {
            exp[i].click();
        };

更多以前的尝试可以在这里看到:如何在 elems 父兄弟选择器上运行 .click?

标签: javascriptregexfor-loopecmascript-6

解决方案


您是否尝试过遍历.k-top元素并查看每个元素以找到您的.k-in?

const expandItemsContaining = (text) => {
  // Let's get all the .k-top divs
  const kTops = document.querySelectorAll('.k-top');

  // And peek into each and every one of them
  kTops.forEach(kTop => {
    // First we check whether there is a .k-in containing your text
    const kIn = kTop.querySelector('.k-in');
    const shouldClick = kIn && kIn.innerText && kIn.innerText.indexOf(text) !== -1;

    // And if there is one we find the .k-i-expand and click it
    if (shouldClick) {
      const kExpand = kTop.querySelector('.k-i-expand');
      if (kExpand) {
        kExpand.click();
      }
    }
  })
}

推荐阅读