The right way parse html to jQuery object

后端 未结 2 1163
梦毁少年i
梦毁少年i 2021-02-14 07:38

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?

<
相关标签:
2条回答
  • 2021-02-14 08:20

    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.

    0 讨论(0)
  • 2021-02-14 08:26

    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 讨论(0)
提交回复
热议问题