Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

javascript - 用JS解析HTML字符串(Parse an HTML string with JS)

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

(我搜索了一个解决方案,但没有任何相关性,所以这是我的问题:)

I want to parse a string which contains HTML text.

(我想解析一个包含HTML文本的字符串。)

I want to do it in JavaScript.

(我想用JavaScript做。)

I tried this library but it seems that it parses the HTML of my current page, not from a string.

(我试过这个库,但它似乎解析了我当前页面的HTML,而不是字符串。)

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.

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

Do you know an API to do it?

(你知道一个API来做吗?)

  ask by stage translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a dummy DOM element and add the string to it.

(创建一个虚拟DOM元素并将字符串添加到它。)

Then, you can manipulate it like any DOM element.

(然后,您可以像任何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' ); // Live NodeList of your anchor elements

Edit: adding a jQuery answer to please the fans!

(编辑:添加一个jQuery答案,以取悦粉丝!)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...