0

HTMLからすべてのテキストを削除し、タグのみを印刷したかったのです。私はこれを書くことになった:

var html = $('html');
var elements = html.find('*');
elements.text('');
alert(html.html());

プリントアウトのみ<head></head><body></body>です。すべてのタグを印刷することを想定していませんでした。HTMLには2000近くのタグがあります。

4

4 に答える 4

5
var elements = html.find('*');
elements.text('');

つまり、「以下htmlのすべての要素を見つけて、それらを空にする」ということです。これにはとが含まれbodyますheadhtmlそれらが空になると、ページ上に他の要素がないため、のコンテンツに表示されるのはそれらだけです。

ページからすべてのテキストを削除して要素を残したい場合は、DOMメソッドを使用して行う必要があります。

html.find('*').each(function() {               // loop over all elements
    $(this).contents().each(function() {       // loop through each element's child nodes
        if (this.nodeType === 3) {             // if the node is a text node
            this.parentNode.removeChild(this); // remove it from the document
        }
    });
})
于 2012-08-27T18:30:03.340 に答える
2

あなたはあなたのdomからすべてを削除しました:

$('html').find('*').text('');

これにより、内のすべてのノードのテキストが<html>空の文字列に設定され、子孫要素が削除されます。残りの2つのノードは、ルートノードの2つの子であり<head></head><body></body>空のテキストノードの子があります。正確に得られた結果です。

すべてのテキストノードを削除する場合は、次を使用する必要があります。

var html = document.documentElement;
(function recurse(el) {
    for (var i=0; i<el.childNodes.length; i++) {
        var child = el.childNodes[i];
        if (child.nodeType == 3)
            el.removeChild(child);
        else
            recurse(child);
    }
})(html);
alert(html.outerHTML);
于 2012-08-27T18:38:45.513 に答える
0

代わりにこれを試してください

$(function(){

    var elements = $(document).find("*");

    elements.each(function(index, data){
        console.log(data);
    });

});

これにより、ページのすべてのhtml要素が返されます。

于 2012-08-27T18:33:45.090 に答える
0

lonesomedayは正しいパスを持っているようですが、次のように文字列を再構築することもできます。

    var htmlString=$('html').html();
    var emptyHtmlString="";
    var isTag=false;

for (i=0;i<htmlString.length;i++)
{
    if(htmlString[i]=='<')
        isTag=true;
    if(isTag)
    {
        emptyHtmlString+=htmlString[i];
    }
    if(htmlString[i]=='>')
        isTag=false;
}
alert(emptyHtmlString);
于 2012-08-27T18:38:33.360 に答える