Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery parseHTML result not as expected

I have HTML in a string from a remote file. Now I want to read some elements with jQuery. The external HTML is here in the string

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <script src="jquery-1.11.1.min.js"></script>
        <script>
            $(document).ready(function() {

                var htmlString = '<!DOCTYPE html>' +
                        '<html>' +
                        '<head>' +
                        '<meta name="firstName" content="false">' +
                        '</head>' +
                        '<body>' +
                        '<div id="test1" class="test1" name="test1">test2</div>' +
                        '<div id="test2" class="test2" name="test2">test2</span>' +
                        '</body>' +
                        '</html>';

                var $ = jQuery;
                var html = $.parseHTML(htmlString);
                //var html = htmlString;

                var test1 = $("#test1", $(html)).attr("name");
                var test2 = $(html).find("div[class='test2']").attr("name");
                var test3 = $(html).attr("name");

                console.log(html);
                console.log('1: ' + test1); //undefined
                console.log('2: ' + test2); //undefined
                console.log('3: ' + test3); //firstName

            });
        </script>
    </head>
    <body>
    </body>
</html>

can someone explain to me why I can not select an item?


1 Answers

$.parseHTML parses out the head and body tags as they are generally not wanted when you insert something into a DOM that already has a head and body tag, so you end up with an array looking like

[meta, div#test1.test1, div#test2.test2]

containing the meta tag and the two div's.

As the div's are now root elements, they are not children of anything, so using jQuery's find() won't work, as it only finds descendant elements.

Using filter() however will work

$(html).filter('.test2').attr("name");

or if you're unsure of wether the elements are root elements or children of some element, you can append the array of elements to a wrapper element, and then use find()

$('<div />', {html : html}).find('.test2').attr('name');

FIDDLE

like image 178
adeneo Avatar answered Jul 13 '26 16:07

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!