After getting a page's content from an AJAX request I can select tag element but cannot select body element

后端 未结 3 1354
不思量自难忘°
不思量自难忘° 2021-01-26 16:27

I got an html page through an AJAX request

$.ajax({
    async: true,
    method: \'GET\',
    url: linkPage,
    // cache: true,
    success: function (data) {
          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 17:28

    It looks like, when given a string like that, jQuery will only save the contents of the body into its collection:

    const data = `
    
    
    ...
    
    
    
    ...
    `; console.log($(data)[0]); console.log($(data)[1]); console.log($(data)[2]);

    (Check your browser console. It's selecting the text nodes around #wrap, and #wrap itself, but not the or )

    You could use DOMParser instead, which will try to turn the whole string into a document, without trying to leave things out:

    const data = `
    
    
    ...
    
    
    
    ...
    `; const doc = new DOMParser().parseFromString(data, 'text/html'); console.log(doc.body.className);

    Another benefit of using DOMParser is that, unlike jQuery, it won't execute possibly-unsafe code in the HTML string:

    const data = `
    
    
    ...
    
    
    
    
    `;
    $(data);
    
    jQuery version, unsafe

    const data = `
    
    
    ...
    
    
    
    
    `;
    const doc = new DOMParser().parseFromString(data, 'text/html');
    console.log(doc.body.className);
    DOMParser version, safe

提交回复
热议问题