JQuery parseHTML result is not as expected
I have HTML in line from a remote file. Now I want to read some elements using jQuery. The outer HTML is here in the line
<!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 cant select an item?
$.parseHTML
parses tags head
and body
, since they are usually not needed, when you insert something into the DOM that already has a tag head
and body
so you end up with an array that looks like
[meta, div#test1.test1, div#test2.test2]
containing a meta tag and two divs.
Since divs are now root elements, they are not children, so using jQuery find()
won't work as it only finds child elements .
Using filter()
however will work
$(html).filter('.test2').attr("name");
or if you are not sure if the elements are the root elements or children of some element, you can add an array of elements to the wrapper element and then use find()
$('<div />', {html : html}).find('.test2').attr('name');
source to share