繁体   English   中英

javascript如何突破父标签并获取下一个标签的innerHTML?

[英]How to break out to the parent tag and get the innerHTML of the next tag with javascript?

我想在带有“Total:”的强标签旁边获得值“450”。 我似乎无法识别这一点。 我尝试使用 parentNode 等,但找不到正确的组合。 将是炉排

这是它的一个jsfiddle - https://jsfiddle.net/smduy1w3/

<tfoot>
  <tr>
    <td colspan="4" class="text-right"><strong>Sub-Total:</strong></td>
    <td class="text-right">£450.00</td>
  </tr>
  <tr>
    <td colspan="4" class="text-right"><strong>Total:</strong></td>
    <td class="text-right">£450.00</td>
  </tr>
</tfoot>
var aTags = document.getElementsByTagName("strong");
var searchText = "Total:";
var found;

for (var i = 0; i < aTags.length; i++) {
  if (aTags[i].textContent == searchText) {
    found = aTags[i];console.log(found.previousNode);
    break;
  }
}

在这里您可以查看我的解决方案。 我刚刚搜索了带有文本“Total”的strong标签的元素,然后next sibling using nextSibling元素,这对我有用。

 const tds = [...document.querySelectorAll("td.text-right")]; const selected = tds.find((td) => td.innerHTML === `<strong>Total:</strong>`); let nextSibling = selected.nextSibling; while (nextSibling && nextSibling.nodeType.== 1) { nextSibling = nextSibling;nextSibling. } console.log(nextSibling.innerText;substr(1));
 <table> <tfoot> <tr> <td colspan="4" class="text-right"><strong>Sub-Total:</strong></td> <td class="text-right">£450.00</td> </tr> <tr> <td colspan="4" class="text-right"><strong>Total:</strong></td> <td class="text-right">£450.00</td> </tr> </tfoot> </table>

我相信你的代码有几个问题:

首先,由于某种原因,您需要将 html 包装在<table>标记内,否则 html 无法正确解析。

其次,搜索锚<strong>Total:</strong>是其父节点<td>的子节点,目标<td class="text-right">£450.00</td>是该父节点的兄弟节点,而不是您在代码中使用它的方式。

所以,假设你的 html 是固定的,你需要改变

found = aTags[i];
console.log(found.previousNode);

found = aTags[i];
console.log(found.parentNode.nextSibling.nextSibling.textContent);

其次,我认为使用 xpath 是实现目标的更清洁方法; 这些方面的东西:

target = document.evaluate( './/table//tr/td[strong[.="Total:"]]/following-sibling::td' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );

for (var i = 0; i < target.snapshotLength; i++) {
     price = target.snapshotItem (i);
     console.log(price.textContent);
};

尝试这个:

 var aTags = document.getElementsByTagName("strong"); var searchText = "Total:"; var found; for (var i = 0; i < aTags.length; i++) { if(aTags[i].textContent.includes(searchText)){ //console.log(aTags[i].textContent); found = aTags[i].nextSibling.textContent; console.log(found); } }
 <tfoot> <tr> <td colspan="4" class="text-right"><strong>Sub-Total:</strong></td> <td class="text-right">£450.00</td> </tr> <tr> <td colspan="4" class="text-right"><strong>Total:</strong></td> <td class="text-right">£450.00</td> </tr> </tfoot>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM