最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The right way parse html to jQuery object - Stack Overflow

programmeradmin1浏览0评论

I want to parse a html string to jQuery object then find an element by ID.

I tried 3 ways bellow, but only the last works. I don't know why the others not works?

var html = "<html><body><div id='main'></div></body></html>";

// Not work, return 0
console.log($(html).find('#main').length); 
// Not work, return 0
console.log($($.parseHTML(html)).find('#main').length); 
// Works, return 1
console.log($("<html/>").html(html).find('#main').length); 

Here is the sample: /

I want to parse a html string to jQuery object then find an element by ID.

I tried 3 ways bellow, but only the last works. I don't know why the others not works?

var html = "<html><body><div id='main'></div></body></html>";

// Not work, return 0
console.log($(html).find('#main').length); 
// Not work, return 0
console.log($($.parseHTML(html)).find('#main').length); 
// Works, return 1
console.log($("<html/>").html(html).find('#main').length); 

Here is the sample: http://jsfiddle.net/nbyofkam/2/

Share Improve this question asked Aug 13, 2014 at 8:28 andyfandyf 3,3403 gold badges25 silver badges37 bronze badges 3
  • 1 $(html) == <div id="main"></div> that's why you can't use .find() to find it. – Anton Commented Aug 13, 2014 at 8:31
  • 1 You can also treat the string as an XML console.log($($.parseXML(html)).find('#main').length) but its better to avoid unnecessary wrapping. – Yury Tarabanko Commented Aug 13, 2014 at 8:36
  • 1 I'm puzzled... seems to me that @YuryTarabanko has given the correct answer here. Had a similar problem, und using parseXML instead pf parseHTML helps. – Zane Commented Nov 8, 2016 at 23:39
Add a comment  | 

2 Answers 2

Reset to default 10

It's documented :

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser"s .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

As a result, $(html) is reduced to "<div id="main"></div>". You can verify that by logging $(html)[0].outerHTML.

So you can't use find without wrapping it, which is what you do.

An alternate way to do this -

var myTestDiv = document.createElement('div');
var mystr = '<div id="main"></div>';
myTestDiv.innerHTML = mystr;

console.log(myTestDiv.querySelector('div#main'));
发布评论

评论列表(0)

  1. 暂无评论