【发布时间】: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
我怎样才能只得到“<p>some text</p>”?
【问题讨论】:
标签: jquery html filter selector
代码 sn-p:
<div id="some_text">
<p>some text</p>
<div id="child">
<p>some other text</p>
</div>
</div
我怎样才能只得到“<p>some text</p>”?
【问题讨论】:
标签: jquery html filter selector
$('#some_text:first-child').html(); //contains your text
$('#some_text:first-child').remove(); //to remove
【讨论】:
$('#sometext > p') 应该可以解决问题。
【讨论】:
$("#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 放在哪里?之前呢?后?大约?您可能需要更具体地说明这一点。
【讨论】:
我尽量避免使用 :first-child :parent for :nth child 之类的伪选择器,因为 IE 7 无法识别它。
【讨论】: