如何提取不带/不包含文本的HTML标记

时间:2016-01-19 05:58:36

标签: javascript jquery html

如何只提取包含没有文字的属性的标签?

来源:

<div style='some style' id='some id'>
some text
</div>
<a href='some url'>some link</a>
<img src='some url' />

结果:

"<div style='some style' id='some id'> </div> <a href='some url'> </a> <img src='some url' />"

2 个答案:

答案 0 :(得分:2)

试试这个:

sample = $("<div><div style='some style' id='some id'>some text</div><a href='some url'>some link</a><img src='some url' /></div>");
output = removeText(sample);

function removeText(node){
    node = $(node);
    $.each( node.contents(), function(){
        if(this.nodeType == 3) {
            this.parentNode.removeChild(this);
        }else {
            removeText(this);
        }

    });
    return node;
} 

输出:

<div><div style="some style" id="some id"></div><a href="some url"></a><img src="some url"></div>

答案 1 :(得分:0)

你可以使用jquery'clone':

    <div id="some-id">lalala</div>

    var $copy = $('#some-id').clone().html('');//create a copy and remove text
    var str = $('<div>').append($copy);//covert jquery obj to string

try it in console