0

代码片段:

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

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

</div

我怎么只能得到“ <p>some text</p>”?

4

4 回答 4

0
$('#some_text:first-child').html(); //contains your text

$('#some_text:first-child').remove(); //to remove
于 2009-11-09T23:13:32.403 回答
0

使用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 放在哪里?之前呢?后?大约?您可能需要更具体地说明这一点。

于 2009-11-09T23:13:40.290 回答
0

$('#sometext > p')应该做的伎俩。

于 2009-11-09T23:14:44.413 回答
0

我尽量避免使用像:first-child :parentfor :nthchild 这样的伪选择器,因为 IE 7 无法识别它。

于 2012-08-13T17:03:38.330 回答