I was testing a method with qunit, and i found something i didn't understand.
The function is checking if all descendants of are scanned, i used a variable to calculate the number of occurrences.
test ("all body children highlilighted", function(){
var body = $('<body><form><label>This is a label</label><input type="text" /></form><input type="text" /></body>') ;
scan_body(body) ;
var compteur = 0 ;
body.find('*').each(function(idx, val){
var past_color = $(this).css('background-color') ;
var present_color = $(this).mouseenter().css('background-color') ;
notEqual(past_color, present_color, "We expected the color of this element to be changed") ;
compteur++ ;
}) ;
equal(compteur, 5, "5 expected !!!!") ;
}) ;
the final assertion is always false, compteur contains 2 always. Why ?
The behaviour you're experiencing is because jQuery's $()
, when used to parse HTML string, uses innerHTML
internally (putting your HTML into a <div>
). It is explained in jQuery documentation:
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
And innerHTML
strips out <body>
if you try to put it into a <div>
(JSFiddle):
var div = document.createElement('div');
div.innerHTML = '<body><form></form></body>';
// div == <div><form></form></div>
If not for this, you would see compteur
equal to 4, as per @T.J. Crowder answer.