.find替换html标签内的内容

时间:2012-10-19 10:25:25

标签: jquery

我想从我的wysiwyg中清理html标签。我想用另一个标签替换某些标签。这几乎只有replaceWith()也可以从标签中删除内容。我不想这样做。我只是想替换标签。这是我到目前为止所拥有的。

测试文字:

This<div>is</div><div>a test</div><div>to clean&nbsp;</div><div>some tags</div><div><br></div>

预期结果:

This<p>is</p><p>a test</p><p>to clean</p><p>some tags</p><p><br></p>

实际结果:

This<p></p><p></p><p></p><p></p><p></p>

这是我用来查找和替换

的代码
var thebad = ["h1","h2","h3","h4","h5","h6","div"];
        var thegood = ["","","","","","","<p>"];
        for(var i = 0; i < thebad.length; i++){
            $('.content').contents().find('body').find(thebad[i]).replaceWith(thegood[i]);
        }

我需要弄清楚当我替换它们时如何将文本保留在html标签内。

提前致谢

3 个答案:

答案 0 :(得分:1)

试试这个:

$('div').contents().unwrap().wrap('<p />'); 

编辑:

$('div').replaceWith(function(){ 
    return $("<p />").append($(this).contents()); 
});

答案 1 :(得分:0)

$("div").replaceWith(function() {
    var $div = $(this);
    return $("<p />")
        //.attr('class', $div.attr('class')) // uncomment if you need to give back same class value
        .html($div.html());
});

答案 2 :(得分:0)

试试这个:

var text = $("#test").html();
var replace_tags = { "<div>": "<p>", "</div>": "</p>",  "<div ": "<p "}; //edited
$.each( replace_tags, function(i,v){
     text = text.replace(new RegExp(i, 'g'),v);
});
//console.log(text);

经过测试:

<div id='test'>
    <h1>dummy text</h1>
    <div>dummy text</div>
    <h1>dummy text</h1>
    <p>dummy text</p>
    <div>dummy text</div>
</div>

结果:

<h1>sadsad</h1>
<p>sadsad</p>
<h1>fsdfsd</h1>
<p>dasdasdasdsad</p>
<p>sadsad</p>
相关问题