views:

354

answers:

3

Code snippet :

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

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

</div

How can I only get "<p>some text</p>"?

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

$('#some_text:first-child').remove(); //to remove
Ropstah
+1  A: 

Use replaceWith():

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

or if you need to be more specific:

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

or even use not():

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

replaceWith() will replace each matched element with the specific HTML so if you match more than one you'll get duplicate content. An alternative is to remove it then add the HTML you want.

Basically replacing the HTML inside the div while maintaining the child element is hard because where do you put the new HTML? Before it? After? Around? You probably need to be more specific about that.

cletus
+1  A: 

$('#sometext > p') should do the trick.

Soufiane Hassou