gpt4 book ai didi

javascript - 使用 javascript 从 HTML 表中获取元素

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:26 25 4
gpt4 key购买 nike

这是我的HTML

<td class=​"style1 product name" valign=​"top" nowrap>23$​</td>​, 
<td style=​"padding-left:​10px;​" class=​"product name" width=​"85%">productY</td>​
<td class=​"style1 product name" valign=​"top" nowrap>​10$​</td>​,
<td style=​"padding-left:​10px;​" class=​"product name" width=​"85%">productX</td>​

我尝试了下面的脚本,但它返回了完整的 html。

document.getElementsByClassName("product name")

我怎样才能让它工作,以便它返回数组中的 productX 和 productY?

请告诉我谢谢

最佳答案

类不能包含空格,所以class= "product name"实际上是两个类:productname

鉴于您当前的 HTML,您可以使用 document.querySelectorAll('.product.name:not(.style1)') 获取具有类 productname,同时排除具有 style1 类的那些。

您可以遍历此列表,像这样获取每个元素的文本内容:

var products = document.querySelectorAll('.product.name:not(.style1)'),
a = [],
i;

for(i = 0 ; i < products.length ; i++) {
a.push(products[i].textContent);
}

console.log(a);
<table>
<tr>
<td class="style1 product name" valign="top" nowrap>23$</td>
<td style="padding-left:10px;" class="product name" width="85%">productY</td>
<td class="style1 product name" valign="top" nowrap>10$</td>
<td style="padding-left:10px;" class="product name" width="85%">productX</td>
</tr>
</table>

关于javascript - 使用 javascript 从 HTML 表中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40643345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com