Javascript 找到匹配文本后,单击特定同级

Javascript 找到匹配文本后,单击特定同级,javascript,regex,for-loop,ecmascript-6,Javascript,Regex,For Loop,Ecmascript 6,我有许多下面的“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="

我有许多下面的“
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

在这里可以看到以前的更多尝试:

您是否尝试过迭代
.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();
      }
    }
  })
}

我创建了一个递归函数,它检查它的所有同级,直到找到一个具有指定innerHTML的同级。如果找不到,则不执行任何操作:

function checkSibling(node) {
  if (node.innerHTML == "unique TEXT99") {
    return true;
  } else if (node.nextSibling) {
    return checkSibling(node.nextSibling);
  } else {
    return false;
  }
}

async function clickOnNode() {
  let exp = document.querySelectorAll(".k-i-expand");
  for await (const node of exp) {
    const hasText = await checkSibling(node);

    if (hasText) {
      console.log("Result: ", hasText);
      node.click();
    }
  }
}

clickOnNode();

我还创建了一个带有代码的应用程序供您使用。我想可以通过正则表达式改进innerHTML检查。

您可以添加更多HTML来说明结构吗?k-top内部是否有多个k-top或多个k-in?
function checkSibling(node) {
  if (node.innerHTML == "unique TEXT99") {
    return true;
  } else if (node.nextSibling) {
    return checkSibling(node.nextSibling);
  } else {
    return false;
  }
}

async function clickOnNode() {
  let exp = document.querySelectorAll(".k-i-expand");
  for await (const node of exp) {
    const hasText = await checkSibling(node);

    if (hasText) {
      console.log("Result: ", hasText);
      node.click();
    }
  }
}

clickOnNode();