Wednesday, 28 February 2018
javascript - The right way parse html to jQuery object
Answer
Answer
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(html).find('#main').length);
// 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($("
Here is the sample:
http://jsfiddle.net/nbyofkam/2/
Answer
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
,
, or
elements. As a result, the elements inserted may not be representative of the original string passed.
As a result, $(html)
is reduced to ""
. You can verify that by logging $(html)[0].outerHTML
.
So you can't use find
without wrapping it, which is what you do.
casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV
In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...
-
The whole error output being: LNK2019 unresolved external symbol wWinMain referenced in function "int __cdecl __scrt_common_main_seh(vo...
-
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradi...
-
I recently used canvas to conert images to webp, using : const dataUrl = canvas.toDataURL('image/webp'); But this takes a lots of ti...
No comments:
Post a Comment