用JS解析一个HTML字符串 [英] Parse an HTML string with JS

查看:129
本文介绍了用JS解析一个HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了一个解决方案,但没有什么是相关的,所以这里是我的问题:

我想解析一个包含HTML文本的字符串。我想用JavaScript来做。



我试过这个库,但它似乎解析了我当前页面的HTML,而不是字符串。因为当我尝试下面的代码时,它会改变我的页面标题:

  var parser = new HTMLtoDOM(< html> ;< head>< title> titleTest< / title>< / head>< body>< a href ='test0'> test01< / a>< a href ='test1'> test02< / a>< a href ='test2'> test03< / a>< / body>< / html>,document); 

我的目标是从我读取的HTML外部页面中提取链接,就像字符串一样。 p>

您知道一个API来执行它吗?

解决方案

DOM元素并将字符串添加到它。然后,您可以像处理任何DOM元素一样操作它。

  var el = document.createElement('html'); 
el.innerHTML =< html>< head>< title> titleTest< / title>< / head>< body>< a href ='test0'> test01< / a> < a href ='test1'> test02< / a>< a href ='test2'> test03< / a>< / body>< / html>

el.getElementsByTagName('a'); //你的锚元素的实时NodeList

编辑:添加一个jQuery的答案, p>

  var el = $('< div>< / div>'); 
el.html(< html>< head>< title> titleTest< / title>< / head>< body>< a href ='test0'> test01< / a> < a href ='test1'> test02< / a>< a href ='test2'> test03< / a>< / body>< / html>);

$('a',el)//所有锚元素


I searched for a solution but nothing was relevant, so here is my problem:

I want to parse a string which contains HTML text. I want to do it in JavaScript.

I tried this library but it seems that it parses the HTML of my current page, not from a string. Because when I try the code below, it changes the title of my page:

var parser = new HTMLtoDOM("<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>", document);

My goal is to extract links from an HTML external page that I read just like a string.

Do you know an API to do it?

解决方案

Create a dummy DOM element and add the string to it. Then, you can manipulate it like any DOM element.

var el = document.createElement( 'html' );
el.innerHTML = "<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>";

el.getElementsByTagName( 'a' ); // Live NodeList of your anchor elements

Edit: adding a jQuery answer to please the fans!

var el = $( '<div></div>' );
el.html("<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>");

$('a', el) // All the anchor elements

这篇关于用JS解析一个HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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