如何在获取html()jQuery时转义元素

时间:2014-07-11 09:39:43

标签: jquery html

<div id="template">
    <p id="para">
        <h3>I should not come in html</h3>

            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.


    </p>
    <h1>Only comes in html</h1>
</div>

注意 -

我想将div #template的整个html除外,其中包含元素#para

如何使用jQuery过滤?

我的jQuery尝试这个 -

$(function(){
    $('body').append(function(){
        $('#template').html().filter($('#para').html());
    });
});

小提琴 - http://jsfiddle.net/JM9nH/

2 个答案:

答案 0 :(得分:1)

这将做你想要的事情

$("#template").children().not("#para").html();

你不应该把h3放在段落中......你的jsfiddle updated(看看控制台)

答案 1 :(得分:0)

首先,您的所有HTML都是invalidthere is a div in p tag我们无法在div标签中嵌套p标记

HTML

<div id="template">
    <div id="para">
         <h3>I should not come in html</h3>

        <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</div>
    </div>
     <h1>Only comes in html</h1>

</div>

JS

var getHtmlData=$('#template').children().filter(function(i,val){
   return !(this.id=="para");
});
$('#template').html(getHtmlData);

DEMO

OP

Only comes in html

使用children选择父级的直接子级,并使用filter删除所选元素的不需要的子级