【问题标题】:Jquery html attribute : How to exclude an element's child's html from that element's htmlJquery html属性:如何从该元素的html中排除元素的子html
【发布时间】:2009-11-09 23:10:36
【问题描述】:

代码 sn-p:

<div id="some_text">
    <p>some text</p>

    <div id="child">
        <p>some other text</p>
    </div>

</div

我怎样才能只得到“&lt;p&gt;some text&lt;/p&gt;”?

【问题讨论】:

    标签: jquery html filter selector


    【解决方案1】:
    $('#some_text:first-child').html(); //contains your text
    
    $('#some_text:first-child').remove(); //to remove
    

    【讨论】:

      【解决方案2】:

      $('#sometext &gt; p') 应该可以解决问题。

      【讨论】:

        【解决方案3】:

        使用replaceWith():

        $("#some_text > p").replaceWith("some other html");
        

        或者如果您需要更具体:

        $("#some_text > p:first-child").replaceWith("some other html");
        

        甚至使用not():

        $("#some_text").children().not("#child").replaceWith("some other html");
        

        replaceWith() 将用特定的 HTML 替换 每个 匹配的元素,因此如果匹配多个元素,您将获得重复的内容。另一种方法是将其删除,然后添加所需的 HTML。

        基本上在保留子元素的同时替换 div 中的 HTML 很困难,因为您将新的 HTML 放在哪里?之前呢?后?大约?您可能需要更具体地说明这一点。

        【讨论】:

          【解决方案4】:

          我尽量避免使用 :first-child :parent for :nth child 之类的伪选择器,因为 IE 7 无法识别它。

          【讨论】:

            猜你喜欢
            • 2012-10-24
            • 1970-01-01
            • 1970-01-01
            • 2015-10-13
            • 1970-01-01
            • 2018-06-21
            • 2016-03-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多