在Javascript中的2个标签之间提取数据 [英] Extracting data between 2 tags in Javascript

查看:139
本文介绍了在Javascript中的2个标签之间提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个js新手。我试图从一个非常旧且过时的网页中获取表格,这个网页不断更新(本地)并将其添加到不同的页面。

I'm a js newbie. I'm trying to get a table from a really old and outdated webpage that is continually updated (locally) and add it to a different page.

我需要从以下示例中提取表1。如果你能解释你的解决方案是如何工作的话,奖励点数

I need to extract table 1 from the following example. Bonus points if you can explain how your solution works.

<html>
<head>
</head>
<div> This is table 1 </div>
<table>
    <tr>
       <td>
         <a>
         </a>
       </td>
    </tr>
</table>
<div> This is table 2 </div>
<table>
    <tr>
       <td>
         <a>
         </a>
       </td>
    </tr>
</table>
</html>

谢谢!

推荐答案

另一个简短的方法是使用 DOMParser
DOMParser.parseFromString会将您的html代码解析为DOMDocument对象。 DOMDocument对象具有body对象。而身体又有孩子。您的table1是该列表中的第二个孩子。

Another shorter way is using DOMParser. DOMParser.parseFromString will parse your html code into DOMDocument object. DOMDocument object has body object. And in turn body has children. Your table1 is the 2nd child in that list .

let source = "..." //your html text above
// method 1: use DOMParser
let dom = (new DOMParser()).parseFromString(source, 'text/html')
let table1 = dom.body.children[1]

试试这个 https://codepen.io/minht/pen/EXbgXY?editors=0010#0

这篇关于在Javascript中的2个标签之间提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆