代码片段:
<div id="some_text">
<p>some text</p>
<div id="child">
<p>some other text</p>
</div>
</div
我怎么只能得到“ <p>some text</p>
”?
$('#some_text:first-child').html(); //contains your text
$('#some_text:first-child').remove(); //to remove
$("#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 放在哪里?之前呢?后?大约?您可能需要更具体地说明这一点。
$('#sometext > p')
应该做的伎俩。
我尽量避免使用像:first-child
:parent
for :nth
child 这样的伪选择器,因为 IE 7 无法识别它。