jQuery过滤器标签并以html身份加入

时间:2014-10-07 20:11:08

标签: jquery filter tags

例如,我有HTML代码:

aaa<b>aaa</b><div class="inptag">ccc</div> ccc cc <strong>zczczc</strong>  <a href="d">aaaa</a>

我想只留下div.inptag标签,并删除所有其他标签,但将innerText保留在其他标签上。

我写了jQuery代码:

dat = $('<div/>').html('aaa<b>aaa</b><div class="inptag">ccc</div>')
.find('*:not(div.inptag,div.inptag>div.typ,div.inptag>input)').contents().unwrap();

...而且我不知道如何将结果作为标准HTML代码。现在我[object Object]和.join(&#39;&#39;)无效。

1 个答案:

答案 0 :(得分:1)

我假设你想要一个字符串作为输出?如果是这样,这看起来可以满足您的需求。

var inputStr = 'aaa<b>aaa</b><div class="inptag">ccc</div> ccc cc <strong>zczczc</strong>  <a href="d">aaaa</a>', 
    elt = $('<div/>').html(inputStr), //jquery will convert this to DOM elements
    badTags = elt.find(':not(div.inptag)'), //find the elements that are not divs with a class of inptag
    index,
    outputStr = '' + inputStr; //making a copy of inputStr

//cycle through all of the bad tags that we found
for(index = 0; index < badTags.length; index++) {
    //replace any instances of the outer html with instances of the inner text
    outputStr = outputStr.replace(badTags[index].outerHTML, badTags[index].innerText);
}

alert(outputStr);

小提琴here