문제

I can navigate the elements perfectly fine in Chrome's console, but I cannot seem to get a reference to the nested DocumentFragment with childNodes or firstChild.

Here's the code in jsFiddle: http://jsfiddle.net/Ge8au/2/

Here's the code:

function withoutJquery(html)
{
    var temp = document.createElement("div");
    temp.innerHTML = html;

    var fragment = document.createDocumentFragment();
    var child;

    while (child = temp.firstChild)
    {
        fragment.appendChild(child);
    }

    return fragment.firstChild;
}


function withJquery(html)
{
    var fragment = document.createDocumentFragment();

    fragment.appendChild( jQuery.buildFragment([html],document) );

    return fragment.firstChild;
}


var ajaxHTML = "";
ajaxHTML += "<template>\n";
ajaxHTML += "    <div>asdf</div>\n";
ajaxHTML += "    <div>\n";
ajaxHTML += "        <span>asdf</span>\n";
ajaxHTML += "    </div>\n";
ajaxHTML += "</template>";


// Gives the <template>
console.log( withoutJquery(ajaxHTML) );
console.log( withJquery(ajaxHTML) );

// Where are the <div>'s?
console.log( withoutJquery(ajaxHTML).childNodes.length );
console.log( withJquery(ajaxHTML).childNodes.length );
도움이 되었습니까?

해결책

Try returning fragment.firstChild.content instead of fragment.firstChild.

Since this appears to vary slightly by browser, a better solution would be something like this:

var toReturn = fragment.firstChild;
return (toReturn.content ? toReturn.content : toReturn.childNodes);

It looks like there's some confusion by browser about whether the childNodes is needed as well - with the above code, you can probably remove childNodes from the console.log() statements.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top